[英]explicit constructor in std::runtime_error
According to cplusplus.com, this is the implementation of the std::runtime_error class: 根据cplusplus.com,这是std :: runtime_error类的实现:
class runtime_error : public exception {
public:
explicit runtime_error (const string& what_arg);
};
Since the constructor is explicit, I expected it to only accept std::string objects. 由于构造函数是显式的,我希望它仅接受std :: string对象。
throw std::runtime_error("error message");
This code compiles (GCC), though. 但是,此代码会编译(GCC)。 Shouldn't the compiler complain about the implicit const char* to const string conversion?
编译器是否应该抱怨隐式const char *到const字符串转换?
That is not what explicit means here. 这不是明确的意思。 Maybe it is easiest to illustrate it with an example:
也许用一个例子最简单地说明一下:
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
}
Here, the explicit
converting constructor means you cannot implicitly construct a Foo
from an std::string
. 在这里,
explicit
转换构造函数意味着您不能从std::string
隐式构造Foo
。 But you can still construct an std::string
from a const char*
. 但是您仍然可以从
const char*
构造std::string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.