|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Defined in header <exception> | ||
using exception_ptr=/*unspecified*/ | (since C++11) | |
std::exception_ptr is a nullable pointer-like type that manages an exception object which has been thrown and captured withstd::current_exception. An instance ofstd::exception_ptr may be passed to another function, possibly on another thread, where the exception may be rethrown and handled with acatch clause.
A default-constructedstd::exception_ptr is a null pointer; it does not point to an exception object.
Two instances ofstd::exception_ptr compare equal only if they are both null or both point at the same exception object.
std::exception_ptr is not implicitly convertible to any arithmetic, enumeration, or pointer type. It is contextually convertible tobool, and will evaluate tofalse if it is null,true otherwise.
The exception object referenced by anstd::exception_ptr remains valid as long as there remains at least onestd::exception_ptr that is referencing it:std::exception_ptr is a shared-ownership smart pointer (note: this is in addition to the usualexception object lifetime rules).
std::exception_ptr meets the requirements ofNullablePointer.
#include <exception>#include <iostream>#include <stdexcept>#include <string> void handle_eptr(std::exception_ptr eptr)// passing by value is OK{try{if(eptr)std::rethrow_exception(eptr);}catch(conststd::exception& e){std::cout<<"Caught exception: '"<< e.what()<<"'\n";}} int main(){ std::exception_ptr eptr; try{[[maybe_unused]]char ch=std::string().at(1);// this generates a std::out_of_range}catch(...){ eptr=std::current_exception();// capture} handle_eptr(eptr); }// destructor for std::out_of_range called here, when the eptr is destructed
Possible output:
Caught exception: 'basic_string::at: __n (which is 1) >= this->size() (which is 0)'
(C++11) | creates anstd::exception_ptr from an exception object (function template)[edit] |
(C++11) | captures the current exception in astd::exception_ptr (function)[edit] |
(C++11) | throws the exception from anstd::exception_ptr (function)[edit] |