Reputation: 771
matrix m1(5,5);
matrix m2(5,5);
m1 = matrix(m2);
For the above code (for an arbitrary class, matrix), will the destructor be called for the information associated with m1, when the information of m2 is copied over to it?
Upvotes: 5
Views: 1349
Reputation: 726509
No, an assignment operator will need to deal with releasing whatever resources m1
may hold before performing an assignment. The destructor will be called only when m1
is about to go out of scope.
Upvotes: 5
Reputation: 182763
What is this matrix a container of? If it's values, then there's no issue. If it's smart pointers, then there's no issue.
But what if there are ordinary pointers involved? Then it is completely up to the implementation of matrix::operator=(const matrix&)
. If any destructors need to be called in there, it should call them. It doesn't happen by magic and you do have to think about these things.
In general, it's a bad idea to use ordinary container classes to hold ordinary pointers. If the destructors aren't called, you leak memory. If the destructors are called, you crash if you access the same object through another pointer. (Imagine if you have two matrixes that both contain pointers to the same object.)
Since it is difficult and dangerous to use ordinary container classes to handle containers of ordinary pointers. Specialized containers or specialized pointers should be used for this purpose.
Boost, for example, contains specialized container classes specifically for holding pointers. Boost also has a shared pointer class that can be held by ordinary containers.
You just need to decide what should happen. If you do a=b;
, should a
and b
hold pointers to the same underlying objects? Or should new objects be created for a
to point to internally?
Upvotes: 1
Reputation: 4791
No, once an object which is allocated on the stack is constructed it isn't deconstructed until it either goes out of scope or you call its destructor explicitly (which you should probably never do). So in this case, if matrix defines an overloaded operator=(const matrix& rhs) member function then operator=() is called and it copies rhs into m1. Otherwise, the default assignment is used which simply copies all the member variables from the temporary matrix(m2) object into m1, overwriting the previous values of these variables.
Upvotes: 3
Reputation: 1903
I think it depends on if matrix has implemented the destructor properly and how the assignment operator is implemented. If matrix has a working destructor and matrix uses "assignment-swap" (similar to copy-swap idiom) then yes M1 should be freed properly.
To add to that, you don't really need the Matrix(m2) when calling m1 = m2. This is just calling the copy constructor and then assigning a temporary copy to m1. Therefore, useless work is taking place.
Upvotes: 1