Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are move constructors required to be noexcept?

Tags:

I've been reading some contradicting articles in regards whether move constructors/assignment is allowed to throw or not.

Therefore I'd like to ask whether move constructors/assignments are allowed to throw in the final C++11 standard?

like image 248
ronag Avatar asked Feb 12 '12 15:02

ronag


People also ask

Why noexcept for move constructor?

noexcept is nice for two reasons: The compiler can optimize a little better because it doesn't need to emit any code for unwinding a call stack in case of an exception, and. It leads to incredible performance differences at runtime for std::vector (and other containers, too)

Is the default move constructor Noexcept?

Inheriting constructors and the implicitly-declared default constructors, copy constructors, move constructors, destructors, copy-assignment operators, move-assignment operators are all noexcept(true) by default, unless they are required to call a function that is noexcept(false) , in which case these functions are ...

Are move constructor automatically generated?

If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then: No move constructor is automatically generated. No move-assignment operator is automatically generated.

When move constructor is not generated?

The move constructor is not generated because you declared a copy constructor. Remove the private copy constructor and copy assignment. Adding a non-copyable member (like a unique_ptr ) already prevents generation of the copy special members, so there's no need to prevent them manually, anyway.


1 Answers

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

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

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

like image 140
Nicol Bolas Avatar answered Oct 02 '22 09:10

Nicol Bolas