【问题标题】:explicit constructor in std::runtime_errorstd::runtime_error 中的显式构造函数
【发布时间】:2014-07-16 18:39:21
【问题描述】:

根据 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 字符串的转换吗?

【问题讨论】:

  • explicit 不是这样工作的。它可以防止std::string 隐式转换为std::runtime_error,而不是const char * 转换为std::string。那个取决于std::string的构造函数。

标签: c++ constructor explicit


【解决方案1】:

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

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

【讨论】:

  • 请注意,bar("hello") 是错误的,不是,因为 Foo() 是显式的。而是因为它需要两次(链式)转换,这是不允许的(string-literal -> std::string -> Foo)
  • @Nawaz 不错!我将删除那个以避免混淆问题。
猜你喜欢
  • 2015-03-16
  • 2021-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
相关资源
最近更新 更多