Is it safe to pass a reference of an exception object object to a new exception object?

suppose the following:

struct wrapper_exception { std::runtime_error& err; wrapper_exception( std::runtime_error& _e ) : err(e) {} }; try { throw std::runtime_error("foo"); } catch (std::runtime_error& err) { throw wrapper_exception( err); } 

Question: Is it safe to access the runtime_error link inside wrapper_exception after handling it?

+4
source share
1 answer

I really wanted to say that this behavior is undefined.

The standard repeats many times that the lifetime of exception objects ends when the active handler completes differently than by repeatedly throwing an exception, i.e. saying throw; .

Since you are not throwing an exception, the original exception object expires at the end of the catch block, and you end up with a broken link, no different from throwing an object that contains a link to a local variable.

+6
source

Source: https://habr.com/ru/post/1388071/


All Articles