Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an exception use move semantics when thrown in C++11?

http://www.drdobbs.com/cpp/practical-c-error-handling-in-hybrid-env/197003350?pgno=4

In this article Herb Sutter explains that throwing an exception requires a copy of the exception as it's created as a temporary and therefore uses an std::auto_ptr to get round the copy overhead. In light of move semantics being made available in C++11 is this still necessary?

like image 788
Graeme Avatar asked Aug 25 '12 13:08

Graeme


People also ask

What will happen if the exception will be thrown within a constructor C++?

When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.

What is exception thrown in C?

C doesn't support exception handling. To throw an exception in C, you need to use something platform specific such as Win32's structured exception handling -- but to give any help with that, we'll need to know the platform you care about. ...and don't use Win32 structured exception handling.

Can STD move throw?

Yes, throwing move constructors exist in the wild. Consider std::pair<T, U> where T is noexcept-movable, and U is only copyable (assume that copies can throw).


1 Answers

I have just checked, and the Standard allows

  • omitting the copy or move of an object specified by the operand of a throw expression into the exception object
  • omitting the copy or move of the exception object into the catch clause variable of the same type as the exception object if you don't otherwise change the meaning of the program (i.e if you would rethrow and subsequent catches would suddenly see a changed exception object changed by the previous catch block).

Since these omissions are allowed, the spec requires to first regard the source of the copy or move as an rvalue. So this means that the respective objects will be moved if possible. Of course copy and move elision are still allowed as the first choice.


Update

I was notified that the consideration of the exception object initializer of a catch clause parameter as an rvalue initializer will probably be dropped from the Standard (because in general it is not possible for all cases to detect when the behavior of the program is unchanged when omitting a copy/move), so I recommend to not rely on this (second bullet above).

What you can still rely about is the move of a local variable into the exception object, as in throw x; (first bullet above).

like image 130
Johannes Schaub - litb Avatar answered Sep 22 '22 12:09

Johannes Schaub - litb