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:
1 2 3 4 5 |
int main() { S s1, s2; s1 = s2; } |
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:
1 2 3 4 5 6 7 8 9 10 |
S(const S& s) : m_resource(new int) { *m_resource = *s.m_resource; } // ... void swap(S& s) noexcept { std::swap(m_resource, s.m_resource); } |
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:
1 2 3 4 5 6 |
S& operator = (const S& s) { S temp(s); // May throw swap(temp); // Will never throw return *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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include <iostream> #include <utility> using namespace std; struct S { S() : m_resource(new int) { cout << "S()" << endl; *m_resource = 1; } S(const S& s) : m_resource(new int) { cout << "S(const S&)" << endl; *m_resource = *s.m_resource; } S(S&&) = delete; S& operator = (const S& s) { cout << "operator = (const S&)" << endl; S temp(s); // May throw swap(temp); // Will never throw return *this; } S& operator = (S&&) = delete; ~S() { cout << "~S()" << endl; delete m_resource; } void swap(S& s) noexcept { std::swap(m_resource, s.m_resource); } int* m_resource; }; int main() { S s1, s2; s1 = s2; } |
S()
Program output.
S()
operator = (const S&)
S(const S&)
~S()
~S()
~S()