[ACCEPTED]-Are move constructors required to be noexcept?-noexcept

Accepted answer
Score: 30

Are move constructors in general allowed 12 to throw? Yes. Should they? No.

In general, nothing 11 you do within them should be anything that 10 could throw. You shouldn't be allocating 9 memory, calling other code, or anything 8 like that. The only reason to write a move 7 constructor is to abscond with someone else's 6 memory pointers and object references. You 5 should be copying a few basic types and 4 nulling out the values in the other object. Those 3 things shouldn't throw.

So while it is allowed, it's 2 not a good idea. If you're doing it, rethink 1 what you're doing in your move operations.

Score: 5

Here's to shed some further light on this.

It 15 seems that std::vector in particular is picky about 14 whether or not you declare your move constructors 13 with noexcept. If you do, then std::vector will 12 use them. If you don't then std::vector 11 will resort to using your copy constructor 10 instead. At least in some cases. Notably 9 whenever it reshuffles items internally, after 8 an internal array resize.

You can see the 7 effects in this example, where noexcept 6 is not declared:

http://coliru.stacked-crooked.com/a/285cd07a9a52da3b

And in this example, where 5 it is:

http://coliru.stacked-crooked.com/a/d043774ec4c279ec

In the first example, std::vector 4 uses the copy constructor already at the 3 second and third insertion with push_back. In 2 the second example, it does the same operation, but 1 with the move constructor instead.

More Related questions