I’m trying to test my understanding of C++ memory allocation.
For the following program:
{
int a=0;
}
Since a is allocated off the stack it should be freed when the variable goes out of scope, right?
Okay, easy enough. What about this case:
{
Matrix m(50, 20);
}
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.
When that goes out of scope the destructor on m is called? And that desctructor should deallocate (delete) the memory it allocated?
Now it really gets hard:
{
Matrix t;
{
Matrix m(50, 20);
t=m;
}
}
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?
Yes and generally yes.
What happens is that the assignment operator is called:
It is up to you, the implementer of
Matrix, to ensure valid semantics. There are several possible approaches:m‘s data. In this case there are no difficulties with lifetime and ownership. However, in this approach the assignment is costly.tpoint to the same data asm. This may be viable, but will require a lot of care to make sure the lifetime of the data is managed correctly, and that modifying one matrix doesn’t unexpectedly modify the other. One way to do this is by keeping a reference-counted pointer to the data, and using copy-on-write when modifying data. Some older implementations ofstd::stringare of this type.