Reputation: 101
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
Upvotes: 2
Views: 575
Reputation: 26506
yes, the program is valid.
from cppreference:
The exception object referenced by an std::exception_ptr remains valid as long as there remains at least one std::exception_ptr that is referencing it: std::exception_ptr is a shared-ownership smart pointer
in this case eptr
will make sure that the value returned from std::current_exception
will not get out of scope. when in doubt, think that the lifetime of std::exception_ptr
follows the same scoping rules of std::shared_ptr
, since they both "shared-ownership smart pointer"
Upvotes: 3
Reputation: 275740
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.
Upvotes: 2