考虑以下代码:
std::string my_error_string = "Some error message";
// ...
throw std::runtime_error(std::string("Error: ") + my_error_string);
传递给 runtime_error 的字符串是 string 的临时返回的operator+
。假设这个异常被处理如下:
catch (const std::runtime_error& e)
{
std::cout << e.what() << std::endl;
}
字符串的临时返回什么时候operator+
销毁?语言规范对此有什么要说的吗?另外,假设 runtime_error 接受了一个const char*
参数并像这样抛出:
// Suppose runtime_error has the constructor runtime_error(const char* message)
throw std::runtime_error((std::string("Error: ") + my_error_string).c_str());
现在operator+返回的临时字符串什么时候被销毁了?它会在 catch 块尝试打印它之前被销毁吗,这就是为什么 runtime_error 接受 std::string 而不是 const char* 的原因吗?