[英]explicit constructor in std::runtime_error
根据cplusplus.com,这是std :: runtime_error类的实现:
class runtime_error : public exception {
public:
explicit runtime_error (const string& what_arg);
};
由于构造函数是显式的,我希望它仅接受std :: string对象。
throw std::runtime_error("error message");
但是,此代码会编译(GCC)。 编译器是否应该抱怨隐式const char *到const字符串转换?
这不是明确的意思。 也许用一个例子最简单地说明一下:
struct Foo
{
explicit Foo(const std::string& s) {}
};
void bar(const Foo&) {}
int main()
{
Foo f("hello"); // OK: explicit construction from std::string
Foo f2 = std::string("hello"); // ERROR
std::string s;
bar(s); // ERROR
}
在这里, explicit
转换构造函数意味着您不能从std::string
隐式构造Foo
。 但是您仍然可以从const char*
构造std::string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.