为什么std :: runtime_error :: what()返回const char*而不是std :: string const&

Mar*_*tin 2 c++ string exception

为什么std::runtime_error::what()返回const char*而不是std::string const&?在许多情况下,直接返回对嵌入字符串的引用会很方便,并且可以避免一些开销.那么,首先不返回例如对内部字符串的const引用而不提供重载函数的理由是什么?我想它也跟着一个字符串ctor也可以抛出一个异常,但是我没有看到返回一个字符串引用的风险.

sta*_*tiv 5

std::runtime_error继承自std::exception哪个定义,virtual const char* what() const throw();因此最简单的响应是它是函数的重载,并且您可以确定任何标准异常都以这种方式定义它.它可能(取决于实现)可以返回std::string,但它与标准库的其余部分不一致.

我认为what()返回的原因const char*是你可以避免任何可能失败的操作(尤其是可能抛出异常).请考虑以下代码,该代码不应失败

virtual const char* what() const throw() {
    return "An error has occured";
}
Run Code Online (Sandbox Code Playgroud)

但是在下面的代码中,分配std::string可能会失败,抛出异常:

std::string what() const throw() {
    return std::string("An error has occured");
}
Run Code Online (Sandbox Code Playgroud)

如果字符串的构造函数在这里抛出,那么应用程序很可能会崩溃,无论如何,因为函数指定了throw().

使用std::string异常内引入需要分配的内存可能是不可能的(请注意,std::bad_alloc从继承std::exception太).