【发布时间】:2016-09-22 14:53:39
【问题描述】:
我们希望有一个自己的std::runtime_error:runtime_error(const string& arg) 定义。我们根据另一个构造函数来实现这样的构造函数,即std::runtime_error:runtime_error(const char*),例如:
namespace std {
runtime_error::runtime_error(const string& arg)
: runtime_error(arg.c_str()) {
...
}
}
使用 gcc-4.9.1,这是不可能的,因为构造函数 std::runtime_error::runtime_error(const string& arg) 不存在。在 gcc/4.9.1/include/c++/4.9.1/stdexcept 中,我们看到以下内容:
...
class runtime_error : public exception
{
string _M_msg;
public:
/** Takes a character string describing the error. */
explicit
runtime_error(const string& __arg);
virtual ~runtime_error() _GLIBCXX_USE_NOEXCEPT;
/** Returns a C-style character string describing the general cause of
* the current error (the same string passed to the ctor). */
virtual const char*
what() const _GLIBCXX_USE_NOEXCEPT;
};
...
标准明确规定应该有一个显式的runtime_error(const char*) 构造函数。
19.2.6 类 runtime_error [runtime.error]
namespace std {
class runtime_error : public exception {
public:
explicit runtime_error(const string& what_arg);
explicit runtime_error(const char* what_arg);
};
【问题讨论】:
-
"我们按照其他构造函数来实现这样的构造函数" 你为什么要这样做?采用
std::string的那个有一个内置的长度,而另一个必须做一个strlen来计算长度。那只是无意义的浪费时间。此外,您不能在标准库中重写类。 -
@blackpen C++ 标准不允许,因为
namespace std(以及,从 C++17 开始,namespace std[someNumber])是特殊的。 -
@πάνταῥεῖ c++11 在 4.9 中默认不开启。
-
当整个程序的行为未定义时,争论标准合规性似乎毫无意义。