Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use noexcept in assignment operator with copy-and-swap idiom?

The move assignment operator should often be declared noexcept (i.e. to store the type in STL containers). But the copy-and-swap idiom allows both copy- and move- assignment operators to be defined in a single piece of code. What to do with noexcept specifier in this case? The copy construction can throw, but I doubt whether it can violate the noexcept specifier.

// Is it correct considering that T copy constructor can throw?
T& operator=(T other) noexcept;
like image 512
lizarisk Avatar asked Sep 17 '13 11:09

lizarisk


1 Answers

Since the copy is made on the caller's side of the call, it is not part of what your function does. It can therefore not be controlled by your function and consequently, you can not include this information in the noexcept specification.

The only thing you could do is to play it safe and add both options to your noexcept specification. Of course, that means you are getting some false-negatives.

like image 175
Daniel Frey Avatar answered Sep 23 '22 19:09

Daniel Frey