std::runtime_error 中的显式构造函数

hum*_*odz 1 c++ constructor explicit

根据 cplusplus.com,这是 std::runtime_error 类的实现:

class runtime_error : public exception {
public:
  explicit runtime_error (const string& what_arg);
};
Run Code Online (Sandbox Code Playgroud)

由于构造函数是显式的,我希望它只接受 std::string 对象。

throw std::runtime_error("error message");
Run Code Online (Sandbox Code Playgroud)

但是,此代码编译(GCC)。编译器不应该抱怨隐式 const char* 到 const 字符串的转换吗?

jua*_*nza 5

这不是这里明确的意思。也许用一个例子来说明它是最简单的:

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
}
Run Code Online (Sandbox Code Playgroud)

在这里,explicit转换构造函数意味着您不能Foostd::string. 但是您仍然可以std::string从 a构造一个const char*