【问题标题】:why does folly::future BrokenPromise make the const char* constructor explicit?为什么 folly::future BrokenPromise 使 const char* 构造函数显式?
【发布时间】:2018-11-11 03:39:39
【问题描述】:

我注意到 facebook folly::future 库中的 BrokenPromise 定义,我无法理解此处显式 BrokenPromise(const char* type) 构造函数的目的?有必要吗?

class FOLLY_EXPORT BrokenPromise : public PromiseException {
 public:
  explicit BrokenPromise(const std::string& type)
      : PromiseException("Broken promise for type name `" + type + '`') {}

  explicit BrokenPromise(const char* type) : BrokenPromise(std::string(type)) {}
};

https://github.com/facebook/folly/blob/master/folly/futures/Promise.h#L47

【问题讨论】:

    标签: c++ facebook folly


    【解决方案1】:

    1 参数构造函数是转换构造函数。如果该操作不仅仅是重新解释(并且无损),那么大多数编码标准都会说您将其明确化。

    字符串的 BrokenPromise 不仅仅是对字符串的无损重新解释。因此,明确的。

    还有其他原因可以避免隐式转换;例如,如果 char const* 是隐式的,则 BrokenPromise 可能会意外地从 0 构造。

    非显式的情况可能是从一个浮点数构造一个复数;实数是复数的一个子集。

    【讨论】:

    • 谢谢,但是已经有一个显式的 const std::string 构造函数,并且 const char* 将隐式转换为 const std::string&。那么为什么还要定义一个 const char* 构造函数呢?
    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多