Can std::exception_ptr copy constructor throw?

Viewed 172

It seems to me that standard allows std::exception_ptr to not use ref-counting (i.e. std::exception_ptr cctor can be making a copy of exception object it points to). Which would mean following code may never call handle_eptr() and exception can escape main() with related consequences:

#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
 
void handle_eptr(std::exception_ptr eptr) // passing by value is ok  <---- ARE YOU SURE?
{
    try {
        if (eptr) {
            std::rethrow_exception(eptr);
        }
    } catch(const std::exception& e) {
        std::cout << "Caught exception \"" << e.what() << "\"\n";
    }
}
 
int main()
{
    std::exception_ptr eptr;
    try {
        std::string().at(1); // this generates an 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

Am I correct?

1 Answers

Can std::exception_ptr copy constructor throw?

No.

Standard says (latest draft):

[propagation]

exception_­ptr meets the requirements of Cpp17NullablePointer

[nullablepointer.requirements]

No operation which is part of the Cpp17NullablePointer requirements shall exit via an exception.

Related