【发布时间】:2011-01-25 20:28:28
【问题描述】:
考虑以下代码:
std::string my_error_string = "Some error message";
// ...
throw std::runtime_error(std::string("Error: ") + my_error_string);
传递给runtime_error 的字符串是字符串operator+ 返回的临时字符串。假设这个异常被处理如下:
catch (const std::runtime_error& e)
{
std::cout << e.what() << std::endl;
}
string的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* 的原因吗?
【问题讨论】:
-
Nitpick:
std::runtime_error("Error: " + my_error_string);很好,因为my_error_string是字符串类型。您不必在"Error: "上显式调用std::string构造函数并弄乱您的代码。 -
我更喜欢
std::string("Error: ").append(my_error_string)
标签: c++ exception destructor temporary