3 ms·
Um, what's wrong with the simpler if (this == &that) return *this; TFoo tmp(that); swap(tmp); return *this; (Assume swap does not throw, it's
by conistonwater 12y ago
Um, what's wrong with the simpler
if (this == &that) return *this;
TFoo tmp(that);
swap(tmp);
return *this;
(Assume swap does not throw, it's trivial to implement because swapping pointers wouldn't throw.) This way the constructor of tmp takes care of destroying partially-constructed objects and you don't need to do it by hand. It seems like the clean up code just repeats what the compiler would automatically generate for you in a constructor.
[This is from 1997, btw.]
- Sharlin 12y agoYes, the copy-and-swap idiom [1] is the classic "correct" (but somewhat unintuitive) answer to this problem. It was probably not widely known in 1997, though. [1] http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom http://stackoverflow.com/questions/3279543/what-is-the-copy-...
- maxlybbert 12y agoAccording to the article, correctly implementing copy assignment wasn't widely known either.