title: C++ Memory Deallocation
body: <p>I'm trying to test my understanding of C++ memory allocation.</p>
  
  <p>For the following program:</p>
  
  <pre><code>{
      int a=0;
  }
  </code></pre>
  
  <p>Since <code>a</code> is allocated off the stack it should be freed when the variable goes out of scope, right?</p>
  
  <p>Okay, easy enough. What about this case:</p>
  
  <pre><code>{
      Matrix m(50, 20);
  }
  </code></pre>
  
  <p>Let's say there's a matrix class and I'm creating a new one with 50 rows and 20 columns. Obviously not all of the memory can be allocated off the stack because 50 and 20 could be populated at run time. So I'm guessing that somewhere in the constructor, they allocate memory off the heap.</p>
  
  <p>When that goes out of scope the destructor on <code>m</code> is called? And that desctructor should deallocate (delete) the memory it allocated?</p>
  
  <p>Now it really gets hard:</p>
  
  <pre><code>{
      Matrix t;
      {
          Matrix m(50, 20);
          t=m;
      }
  }
  </code></pre>
  
  <p>What happens then? Does t get assigned to the memory location of m? or does it do a copy of the data in m? If t is a reference to m, then what happens when m goes out of scope? Does the destructor on m get called? or does it wait until t goes out of scope to call the destructor of t/m?</p>