Generally, I like to put all my resources into classes maintaining these resources and these tesource maintainer need a copy construct, copy assignment, and a destructor. Depending on the resource, the copy constructor and copy assignment may be deleted.
What is not as obvious is that some classes not maintaining resources directly may need a copy assignment: if you want your copy assignment to be strongly exception safe, you often need to implement the copy assignment. For example, assume your class stores two vectors. The generated copy assgnment does a memberwise assignment. Normally, memberwise assignment is fine. However, if the assgnment to the second vector throws an exception, it is impossible to restore the original state! A better copy assgnment would look like that:
T& T::operator= (T other) {
other. swap(*this);
return *this;
}
Since swap()
can be implemented without throwing, This imolementation is strongly exception-safe.