【发布时间】:2016-07-22 10:14:50
【问题描述】:
鉴于cppreference.com 中关于std::exception_ptr 的示例,以下列方式缩短代码是否合法?
如果所有处理都在 catch-block 内完成,则无需将 std::exception_ptr 存储在外部甚至全局范围内。
#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
【问题讨论】: