5 ms·
This idiom is largely retired in modern C++. It's generally better to simply not implement operator= and take the compiler generated default implementation for
by nly 4y ago
This idiom is largely retired in modern C++.
It's generally better to simply not implement operator= and take the compiler generated default implementation for both copy and move assignment. Then design your class to have semantics such that member-wise assignment does the Right Thing (tm). C style. If you want an idiom for this it's generally called the 'Rule of Zero'
You get swap() for free since std::swap will do the optimal thing.
- beached_whale 4y agoMost of the time. In container like code, copy/swap gives easy strong exception guarantee, but that is rarely needed
- nly 4y agoAchieving exception safety while copying containers, specifically, is generally simple because their states tend to be very easy to reason about. For example, making sure you destroy elements 0 thru [n-1] in a vector if inserting element [n] in to it fails. Move, and thus swap (since it's 3 moves), should essentially always be noexcept (never throw)
- synergy20 4y agoindeed 'rule of 0' made many idioms go away. just use the standard containers along with smart-pointers for 99% use cases and your c++ life suddenly becomes 99% easier, those come with RAII for free.
- charcircuit 4y agoRule of Zero depends on other classes using rule of five.