title: C++ template code resulting in error with delete being called on an object that apparently wasn't properly allocated
body: <p>I am teaching myself c++ templates. I wrote the following code, and I am getting a weird error about a pointer being freed that wasn't allocated. I am guessing that something in my class template constructor isn't actually calling <code>new</code> on the <code>int</code> when I ask for an <code>&lt;int&gt;</code> type of this class. The code is being compiled and run automatically by <code>CodeRunner</code> for mac which I set up to use the <code>clang++</code> compiler for <code>c++</code> files.</p>
  
  <pre class="lang-c++ prettyprint-override"><code>#include &lt;vector&gt;
  #include &lt;iostream&gt;
  
  template &lt;typename T&gt;
  class HeapVal
  {
      public:
          HeapVal(T val) {ptr = new T(val);}
          ~HeapVal() {delete ptr;}
          T get() {return *ptr;}
      private:
          T* ptr;
  };
  
  int main(){
    std::vector&lt; ::HeapVal&lt;int&gt; &gt; vec;
    for(int i = 0; i &lt; 1000; ++i){
      ::HeapVal&lt;int&gt; h(i);
      vec.push_back(h);
    }
    for(int i = 0; i &lt; 1000; ++i){
      std::cout &lt;&lt; vec[i].get() &lt;&lt; std::endl;
    }
    return( 0 );
  }
  </code></pre>
  
  <p>That code results in the following error either during compilation or execution (looks to me like a run-time kind of error).</p>
  
  <pre><code>Untitled(30214) malloc: *** error for object 0x7f82f24007c0: pointer being freed was not allocated
  *** set a breakpoint in malloc_error_break to debug
  Run Command: line 1: 30214 Abort trap: 6           ./"$2" "${@:3}"
  </code></pre>