Talk:Assignment operator (C++)
Appearance
Example code – exception safety
The example given modifies the state of the object before all operations which might throw exceptions have completed; therefore, the example is not exception-safe. Also, it uses a built-in array, which makes exception safety difficult in general (though not for int
s). Using std::vector<int> array;
instead of int *array;
would make exception-safety easier [1]:
class My_Array { int count; std::vector<int> array; public: // Copy constructor My_Array(const My_Array& orig) : count(orig.count), array(orig.array) { /* EMPTY */ } // Non-throwing swap void Swap(My_Array& orig) { using std::swap; swap(count, orig.count); swap(array, orig.array); } My_Array& operator=(const My_Array& rhs) { My_Array tmp(rhs); Swap(tmp); return *this; } };
- I have just refactored the code to be exception-safe. However, I've left the built-in array to show the implementation in case of manual resource management.--Tigrisek 22:22, 20 September 2007 (UTC)
Example code – Koenig Lookup
I have undid the revision since Koenig Lookup would have the same effect in this case, there's no need to complicate the code.
Surely
std::copy(new_array, new_array + other.count, other.array);
should be
std::copy(other.array, other.array + other.count, new_array);
? The code as-written copies from freshly allocated memory over the original :-( 213.248.204.106 (talk) 09:45, 20 October 2008 (UTC)
- You're absolutely right, I've just fixed the code.Tigrisek (talk) 20:32, 22 October 2008 (UTC)
Add somewhere a Reference to "The Anatomy of the Assignment Operator"
Just as background information.