I understand the need for deep copies, and to ensure my code behaves as desired, I am writing a copy ctor, assignment operator, and dtor for my class.
However, it seems to me that in every case, an assignment operator has to do first what the destructor does (deallocate any dynamically allocated memory, to prevent memory leaks), and then what the copy constructor does (make deep copies of all dynamically allocated data and copy those into the instance being constructed).
Is there a case where an assignment operator should conceptually do something other than the following?
class SomeClass{
//member data, copy ctor, dtor
SomeClass& operator=(SomeClass const& rhs){
//what the destructor does
//what the copy constructor does
}
};
The code is practically identical, and seems like a waste of time to rewrite. Other than invoking the destructor directly at the beginning of the assignment operator, I can't think of a way to reuse the copy constructor code I've already written, since I believe doing something like
*this=rhs
would only recursively invoke the assignment operator, since techinically, "this" has already been constructed.
vector
andunique_ptr
were such poorly designed classes! – Barry