gpt4 book ai didi

c++ - c++20前后指定初始化器的不同行为

转载 作者:行者123 更新时间:2023-12-01 12:30:04 24 4
gpt4 key购买 nike

我遇到了这种奇怪的行为,我找不到很好的解释。

下面的代码会在 c++20 之前成功编译,只有在 explicit 时才会失败用来。

struct Square {
int area = 10;

Square() = default; // only if this is explicit will the compile fail
Square(const Square& other) = delete;
Square(Square&& other) = delete;
Square& operator =(Square&& square) = delete;
Square& operator =(const Square& square) = delete;
};

int main() {
Square s = {
.area = 10
};
}

这本身就很奇怪,但是将编译器转换为 c++20 会使上面的代码失败并显示这些错误消息

海湾合作委员会

could not convert brace-enclosed initializer list





no matching constructor for initialization of 'Square'



问题 :
  • 为什么在c++20之前编译成功,除非explicit ?换句话说,会发生什么隐式转换来实现这一点?
  • c++20 中的哪些更改导致此代码无法编译?
  • 最佳答案

    Why does it compile successfully before c++20 ...


    该程序在 C++20 之前格式错误。
    在 C++20 之前的语言中不存在指定的初始化程序。它编译是因为语言扩展。

    What changed in c++20 that made it not compile anymore?


    该程序在 C++20 中仍然格式错误。
    C++20 语言中引入了指定的初始化器,看起来规则与语言扩展的规则略有不同。相关规则是(来自最新草案):

    [dcl.init.list] List-initialization of an object or reference of type T is defined as follows:

    • If the braced-init-list contains a designated-initializer-list, T shall be an aggregate class. ...

    • ...

    [dcl.init.aggr] An aggregate is an array or a class ([class]) with

    • no user-declared or inherited constructors ([class.ctor]),

    • ...


    正如 NathanOliver 所解释的,C++20 之前的语言扩展的行为差异可能与聚合定义的变化有关。

    关于c++ - c++20前后指定初始化器的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62033598/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com