Chapter 41. Object Lifetimes—Part 2
Difficulty: 6
Following from Item 40, this issue considers a C++ idiom that's frequently recommended—but often dangerously wrong.
Critique the following “anti-idiom” (shown as commonly presented).
T& T::operator=( const T& other ) { if( this != &other ) { this->~T(); new (this) T(other); } return *this; }
What legitimate goal does it try to achieve? Correct any coding flaws in this version.
Even with any flaws corrected, is this idiom safe? Explain. If not, how else should the programmer achieve the intended results?
(See also Item 40.)
Solution
This idiom[3] is frequently recommended, and it appears as an example in ...
Get Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.