Longer title: exception safe assignment operator of resource owning objects. Uff. Because the object owns a resource, how do we write an exception safe assignment operator which will have to free up the old and allocate the new resource. By exception safe I don’t mean that it will never throw, that’s not possible. Instead, I mean safe in the sense that it either succeeds OR in case of exceptions the state of assigned to object is exactly as it was prior to the assignment. Like this:

If assignment operator s1 = s2 throws an exception, we want the state of s1 and s2 to be as it was in line #3.

The trick is two fold: 1) a copy constructor is needed, and 2) noexcept swap function. Like this:

Here the copy constructor allocates the new resource first, then copies its content; the swap function just swaps pointers to the resources, which is always a noexcept operation. Having implemented a copy constructor and swap function we can now implement every assignment operator to have a strong exception guarantee like this:

Here’s how it works: we first make a temporary copy, which does the resource allocation. At this stage exceptions can be thrown, but we have not yet modified the assigned to object. Only after the resource allocation succeeds do we perform the noexcept swap. The destructor of your temporary object will take care of cleaning up the currently owned resource (that’s RAII at its best).

Complete listing (assignment.cpp):

S()
S()
operator = (const S&)
S(const S&)
~S()
~S()
~S()

Program output.

Leave a Reply