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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With