Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move constructors and the Strong Exception Guarantee

Just a quick question, on which I cannot find a good reference, especially with regard to current implementations of the future C++0x standard.

Since move constructors can throw, it means that some standard library functions cannot provide the strong exception guarantee (eg. vector<T>::resize()).

There was a proposal to 1) make all standard library move constructors "no throw", and 2) to add compile time checks on user code to ensure that eg. std::pair<std::string, MyType> defines a nothrow move constructor or no move constructor at all.

What happened to this proposal (esp. with respect to this question) ? How is the issue "solved" in the final draft ?

Most importantly, what does it imply for me when I use a recent GCC or MSVC 10 ? Does those implementations of the standard library provide the Strong Exception Guarantee on eg. std::vector<MyTypeWithAThrowingMoveConstructor>::resize() ?

EDIT: I didn't see this question which is clearly related. If there is a consensus on the fact that my question is a duplicate, then close it. However, I am really interested on what is implemented, not what has been discussed.

like image 674
Alexandre C. Avatar asked May 15 '11 21:05

Alexandre C.


People also ask

What is a move constructor?

A move constructor allows the resources owned by an rvalue object to be moved into an lvalue without creating its copy. An rvalue is an expression that does not have any memory address, and an lvalue is an expression with a memory address.

Is Noexcept movable?

This is because the default implementations of these functions which are automatically added to your class if you don't replace them (much like the default destructors) are created with the correct noexcept properties to allow moving the objects.

What is move constructor in C++ with example?

Move constructor moves the resources in the heap, i.e., unlike copy constructors which copy the data of the existing object and assigning it to the new object move constructor just makes the pointer of the declared object to point to the data of temporary object and nulls out the pointer of the temporary objects.

Is move constructor automatically generated?

No move constructor is automatically generated.


1 Answers

I haven't checked the specific implementations, but the general idea is that if the move constructor can throw, the vector will have to copy the elements instead. That way it is possible to roll back in case of an exception.

There is even a helper function move_if_noexcept defined in <utility> to help it decide what to do.

like image 156
Bo Persson Avatar answered Sep 21 '22 16:09

Bo Persson