【问题标题】:relations between all kinds of initialization and constructions?各种初始化和构造之间的关系?
【发布时间】:2017-03-21 13:43:22
【问题描述】:

我问的是不是

Type t{...};

Type t({...});

Type t = {...};

是等价的吗?如果一个有效,另一个也应该得到相同的结果?

如果没有 explicit 修饰符,它们是否等效?

【问题讨论】:

  • 这真的取决于... 以及可用的构造函数。
  • 不,这三个都不一样。 Here's the example 第一个编译,而其他两个没有。
  • here's an example 第二个编译,但不是第一个或第三个
  • @Someprogrammerdude 该示例旨在证明这三种形式实际上并不等同。对于该术语的某些定义,没有要求该示例“有意义”。话虽如此,在大括号初始化的世界中,explicit 确实适用于采用多个参数的构造函数。

标签: c++ c++11 initialization c++14


【解决方案1】:

不,这三种形式都是不同的,并且在不同的情况下可能是独立的。

Here's an example 第一种形式可以编译,但第二种和第三种没有:

class Type {
public:
    explicit Type(int, int) {}
};

int main()
{
    Type t1{1, 2};     // Ok
    Type t2({1, 2});   // error
    Type t3 = {1, 2};  // error
}

Here's the example 第二种形式编译,但第一种和第三种没有:

class Pair {
public:
    Pair(int, int) {}
};

class Type {
public:
    Type(const Pair&) {}
};

int main()
{
    Type t1{1, 2};     // error
    Type t2({1, 2});   // Ok
    Type t3 = {1, 2};  // error
}

Here's an example,由@T.C. 提供,第三种形式可以编译,但第一种和第二种形式不编译:

struct StrangeConverter {
    explicit operator double() = delete;
    operator float() { return 0.0f; }
};

int main() {
  StrangeConverter sc;
  using Type = double;
  Type t1{sc};     // error
  Type t2({sc});   // error
  Type t3 = {sc};  // Ok
}

【讨论】:

  • 作为一个想法,使 1 模棱两可,但不使用显式使 3?
  • @Yakk Type t3 = {1, 2}; 本质上是 Type t3(Type{1, 2}); ,因此需要 Type{1, 2} 才能编译 - 但随后 Type t1{1, 2}; 也会编译。我想不出任何办法。
  • 这是一个contrived corner case,其中第一种和第二种形式都可以编译但做不同的事情。
  • “我找不到让第三种形式编译而第一种形式不编译的方法”。 There you go.
  • @T.C.用您的示例更新了答案。我知道有人会看到并认为"Challenge accepted"
猜你喜欢
  • 1970-01-01
  • 2017-02-07
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 2019-10-07
  • 1970-01-01
相关资源
最近更新 更多