Destructor called on assignment between (stack) variables?

北城余情 提交于 2019-12-05 17:39:00

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.

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!