Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor called on assignment between (stack) variables?

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?

like image 813
Chris Grimm Avatar asked Apr 14 '12 02:04

Chris Grimm


3 Answers

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.

like image 79
Sergey Kalinichenko Avatar answered Oct 09 '22 15:10

Sergey Kalinichenko


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.

like image 39
Davis King Avatar answered Oct 09 '22 13:10

Davis King


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.

like image 40
keelerjr12 Avatar answered Oct 09 '22 13:10

keelerjr12