'Lifetime requirements for storage of std::exception_ptr

Given the example about std::exception_ptr from cppreference.com, would it be legal to shorten the code in the following way? If all the handling is done inside the catch-block, there should be no need to store the std::exception_ptr at an outer or even at global scope.

#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
 
void handle_eptr(std::exception_ptr eptr) // passing by value is ok
{
    try {
        if (eptr) {
            std::rethrow_exception(eptr);
        }
    } catch(const std::exception& e) {
        std::cout << "Caught exception \"" << e.what() << "\"\n";
    }
}
 
int main()
{
    try {
        std::string().at(1); // this generates an std::out_of_range
    } catch(...) {
        handle_eptr(std::current_exception()); // CHANGE: HANDLING THE std::exception_ptr AS R-VALUE INSIDE THE CATCH BLOCK
    }
} // destructor for std::out_of_range called here, when the eptr is destructed


Solution 1:[1]

Sure, but the point of the cppreference code is that the exception pointer allows you to persist the lifetime of the exception outside of the catch block, and without rethrowing.

So your code looks legal, but it would not fullfill the purpose thst the cppreference code does.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yakk - Adam Nevraumont