6 ms·
The copy and swap idiom in C++
- jbandela1 4y agoPost C++11, it is probably better to use the "copy and move" idiom. MyClass& operator=(const MyClass& other) { return (*this) = MyClass(other); }
- vlovich123 4y agoIn any version of the language it's better to decompose it so that you never implement any of these. You either have: 1. A class that's responsible for managing exactly one instance of a resource (e.g. FileDescriptor). This class defines whether or not a resource is copyable and/or movable. 2. A dynamically sized container that needs to offer certain kinds of guarantees. 3. A composite class that may contain zero or more instances of 1, 2, and/or 3. The vast majority of classes you write are always going to be 3. Option 3 should NEVER specify move/copy constructors/assignment operators and instead should inherit that from whatever is being stored. Don't do #2 unless you really know what you're doing. Prefer to use existing well-behaved containers from STL. If you need 3p ones, Folly and Boost are probably good ones. I don't know how ABSEIL fares around exception safety when exceptions are enabled so YMMV there if you're doing things in an exception context. It can be hard to properly make sure that you inherit the copyability / movability from the underlying type (& also noexcept inheritance). For #1, KISS is a very good principle. Just make sure you always leave resources in a consistent state. Move helps here a lot but can be emulated with copy + swap pre-C++11. Here's an example of what a copyable and movable resource might look like: // Terrible idea - don't actually do this in practice. class AutoDupOnCopyFd { public: AutoDupOnCopyFd(const AutoDupOnCopyFd& copy): _fd(dup(copy._fd)) { if (_fd == -1) { throw ... } } AutoDupOnCopyFd(AutoDupOnCopyFd&& owned) noexcept: _fd(std::exchange(copy._fd, -1)) {} ~AutoDupOnCopyFd() noexcept { close(_fd); } AutoDupOnCopyFd& operator=(const AutoDupOnCopyFd& other) { // No need to check for assignment to self but you can if you think you're likely to have this happen // to avoid the syscall (copy to self is typically rare) AutoDupOnCopyFd copy(other); *this = *copy; return *this; } AutoDupOnCopyFd& operator=(AutoDupOnCopyFd&& other) noexcept { using std::swap; swap(_fd, other._fd); return *this; } private: int _fd; }; Now `AutoDupOnCopyFd` can be nested in any composite class & the composite class will automatically inherit the right set of copy / move semantics with correct exception safety. The rule of 0 really is a powerful concept. This breaks down if you start trying to make 1 class responsible for multiple resources. Don't do that. Use resource classes + containers/composite classes to do that. You can also (ab)use unique_ptr for unique ownership although I still prefer explicitly named classes (no confusion with `->` vs `.`, easier to understand for the vast majority of coders). It's a powerful concept to internalize to level up your C++ game but it's only applicable to C++'s ownership model. Rust went a more teachable path that doesn't have these foot guns.
- bbqbbqbbq 4y ago> I don't know how ABSEIL fares around exception safety when exceptions are enabled so YMMV there if you're doing things in an exception context OMG this is my time to shine. I wrote the library for testing Abseil containers for exception-safety. I don't work there anymore but I know they've implemented exception safety tests for a bunch of containers in there, and I remember when I was writing the library we even found a bug in GNU `std::optional`. https://www.youtube.com/watch?v=XPzHNSUnTc4 https://www.youtube.com/watch?v=XPzHNSUnTc4 is the talk I gave at cppCon about this. As a side story, that talk was the first one in the morning and I showed up just before it started on account of my Uber driver missing the highway exit. I had planned to grab some food at the conference but didn't have time so that whole talk I was overstimulated on coffee on an empty stomach trying to keep my composure early in the morning.
- vlovich123 4y agoI'm kind of surprised that ABSEIL even bothers with exception safety since Google builds everything without exceptions. Can you shed some light on why the team decided to invest in making it exception safe?
- its_bbq 4y agoBecause many of the OSS projects using Abseil do use exceptions and that code, as you pointed out, was completely untested with exceptions on.
- AlexanderDhoore 4y agoI used to teach C++ courses as a consultant. This kind of thing was part of the gospel I was trying to spread. Educate my follow software developers on the merits of good C++ memory management. It all felt so powerful and cool. But after some time you realise that nobody is smart enough to keep all of these idioms and arbitrary C++ rules in their head. The only reason I could do it was because I put so much time into preparing my courses. So all of your collegues will keep writing terrible C++ code. And you will be left frustrated that nobody is "doing C++ right". I guess one could chill down and accept the chaos. I chose to leave C++ behind.
- rambojazz 4y agoI loved C++, for a while. I chose to leave its grammar's complexity behind too.
- pjmlp 4y agoC++ is one of my favourite languages, yet I second the feeling, sometimes preaching good practices feels like fighting windmills, so I spend most of my time on languages where I don't need to discuss about the virtues of bounds checking or exceptions every single day.
- billti 4y agoWhen I was "seriously" using C++ I created myself a bunch of flashcards (using the Quizlet app) to regularly test myself (spaced repetition) on various C++ idioms and rules; such as when to implement which copy/assignment/move constructors and the correct patterns, how to use std::forward correctly, the footguns in various types of casting or initialization, etc. I recently had cause to start using C++ again and went over the cards after about a year break. It was depressing how few I could answer correctly. C++ is great if you're great with it, but that takes a __lot__ of effort, and it can be a minefield otherwise.
- 0xfaded 4y agoI have a notebook I filled with Q&As for every point in The CPP Programming Language that surprised me. It's about 40 pages I occasionally read through, though I've been meaning to convert it to spaced repetition.
- deleted 4y ago[deleted]
- nly 4y agoThis 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.
- dataflow 4y agoCopy-and-swap/move is fun and all, but what they don't point out to you about it is that it prevents the base class operator= from being called when there's inheritance (because it's bypassing operator= entirely). i.e. it might be fine at the app-level since you might know all your callers in that case, but you shouldn't do it in a library that others might want to use, or your code will behave erratically.
- deleted 4y ago[deleted]
- stefanos82 4y agoI have managed to convince myself to think C++ is actually a DIY Tool Center that offers me an abundant set of tools I can choose from, upon need (project-wise). This way I know I don't need to learn the whole language at this particular time; only the necessary parts I can use to produce the desired output, which really helps me control my stress.