title: C++ basics, vectors, destructors
body: <p>I'm a little confused about the best practice for how to do this. Say I have a class that for example allocs some memory. I want it to self destruct like an auto but also put it in a vector for some reason unknown.</p>
  
  <pre><code> #include &lt;iostream&gt;
   #include &lt;vector&gt;
   class Test {
   public:
    Test();
    Test(int a);
    virtual ~Test();
    int counter;
    Test * otherTest;
   };
  
   volatile int count = 0;
  
  
   Test::Test(int a) {
    count++;
    counter = count;
    std::cout &lt;&lt; counter &lt;&lt;  "Got constructed!\n";
    otherTest = new Test();
    otherTest-&gt;counter = 999;
   }
  
   Test::Test() {
    count++;
    counter = count;
    std::cout &lt;&lt; counter &lt;&lt;  "Alloced got constructed!\n";
    otherTest = NULL;
   }
  
  
   Test::~Test() {
    if(otherTest != 0){
    std::cout &lt;&lt; otherTest-&gt;counter &lt;&lt; " 1Got destructed" &lt;&lt; counter &lt;&lt; "\n";
    otherTest-&gt;counter = 888;
    std::cout &lt;&lt; otherTest-&gt;counter &lt;&lt; " 2Got destructed" &lt;&lt; counter &lt;&lt; "\n";
    }
   }
  
   int vectorTest(){
    Test a(5);
    std::vector&lt;Test&gt; vecTest;
    vecTest.push_back(a);
    return 1;
   }
  
   int main(){
    std::cout &lt;&lt; "HELLO WORLD\n";
    vectorTest();
    std::cout &lt;&lt; "Prog finished\n";
   }
  </code></pre>
  
  <p>In this case my destructor gets called twice all from counter 1, the alloc' object has already been set to 888 (or in a real case freed leading to bad access to a deleted object). What's the correct case for putting a local variable into a vector, is this some kind of design that would never happen sensibly. The following behaves differently and the destructor is called just once (which makes sense given its an alloc).</p>
  
  <pre><code> int vectorTest(){
    //Test a(5);
    std::vector&lt;Test&gt; vecTest;
    vecTest.push_back(*(new Test(5)));
    return 1;
   }
  </code></pre>
  
  <p>How can I make the local variable behave the same leading to just one call to the destructor? Would a local simply never be put in a vector? But aren't vectors preferred over arrays, what if there are a load of local objects I want to initialize separately and place into the vector and pass this to another function without using free/heap memory? I think I'm missing something crucial here. Is this a case for some kind of smart pointer that transfers ownership? </p>