Is it possible to use an exception outside the catch statement if it is stored in std :: exception_ptr?

I have std::exception_ptr with an exception inside it. I am going to call std::rethrow_exception to get the actual exception, will the exception be valid after the catch statement? I assume that since I still hold std::exception_ptr , it will still be valid.

See an example:

 std::exception_ptr ePtr = initialize_somewhere_else(); std::runtime_error* a=NULL; try { std::rethrow_exception(ePtr); } catch(std::runtime_error& e) { a = &e; } std::cout << a << ", " << a->what() << std::endl; 

Note. In my tests using Clang, this works.

+5
source share
1 answer

Is it possible to use an exception outside the catch statement if it is stored in std :: exception_ptr?

Yes. You can think of exception_ptr as a pointer counted by an exception link. The exception will continue until exception_ptr refers to it, and will no longer be.

In addition, rethrow_exception does not create a copy.

Sorry, I think I gave the wrong answer.

Here is the detection test:

 #include <iostream> #include <exception> #include <stdexcept> int main() { auto ePtr = std::make_exception_ptr(std::runtime_error("some text")); std::runtime_error* a = nullptr; try { std::rethrow_exception(ePtr); } catch(std::runtime_error& e) { a = &e; } *a = std::runtime_error("other text"); try { std::rethrow_exception(ePtr); } catch(const std::runtime_error& e) { std::cout << e.what() << '\n'; } } 

In gcc and clang outputs:

 other text 

This means that a and ePtr refer to the same object.

However, VS, the current version according to http://webcompiler.cloudapp.net produces:

 some text 

This means that a and ePtr refer to different objects.

Now the question is whether VS is consistent in this regard. My opinion is that it does not really matter. This is a controversial area of ​​the standard, and if it is disputed, the standard will be amended in accordance with existing practice.

It seems to me that rethrow_exception makes a copy on VS, which means that the lifetime of e in the original question is not guaranteed by binding to ePtr .

+3
source

All Articles