Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception safe code and move semantics

Tags:

c++

c++11

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?

like image 962
Evgeny Lazin Avatar asked Oct 25 '13 09:10

Evgeny Lazin


2 Answers

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.

like image 82
ice-phoenix Avatar answered Nov 07 '22 06:11

ice-phoenix


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?

like image 33
HaMster Avatar answered Nov 07 '22 04:11

HaMster