I want to write container class. This container has insert method that have two specializations - first uses copy constructors to copy data from one container to another container element wise. If copy constructor throws exception I just undo all changes to the container like nothing happens.
The second specialization uses move constructor and thats the place where things got complicated. When I move items from one container to another container element by element, move constructor can throw exception. If this happens - I've got really messy state when some elements are moved and other elements stays in it's original places. If I try to move elements back - I can get another exception.
Is it possible to write something like this in exception safe manner or exception safety and move semantics are mutually exclusive?
Use std::move_if_noexcept when writing exception-sensitive code, but still want to use move semantics when it's compile-time safe to do so.
See Scott Meyers' talk at GoingNative 2013 for more details on that.
PS: Oh yes, pls remember that if your stuff is not copy constructible, you're gonna move it regardless of throw/nothrow of your move constructor.
Using constructor delegation is one way to do this. If the non-delegating constructor (probably one without arguments, setting your members to defaults) has finished and the constructor delegating throws, the standard says that your local state is deleted. This way you can't leak. I learned this just today in this talk.
By the way: what type of container are you implementing that the STL has not already set up for you?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With