C++20 结构体是否具有带参数的编译器生成构造函数?

huangapple go评论71阅读模式
英文:

Do C++20 structs have a compiler-generated constructor with parameters?

问题

I was surprised to see that this compiles in C++20 (GCC):

#include <iostream>

struct Test {
    int a;
    int b;
};

void main() {
    Test myTest(1, 2);
    std::cout << myTest.b; // 2
}

Changing struct to class or switching to C++17 throws the error I expected:

error: no matching function call to 'Test::Test(int, int)'

I tried googling, but could not find anything relevant. In C++20, is there a new kind of compiler-generated constructor for structs?

英文:

I was surprised to see that this compiles in C++20 (GCC):

#include &lt;iostream&gt;

struct Test {
    int a;
    int b;
};

void main() {
    Test myTest(1, 2);
    std::cout &lt;&lt; myTest.b; // 2
}

Changing struct to class or switching to C++17 throws the error I expected:

error: no matching function call to &#39;Test::Test(int, int)&#39;

I tried googling, but could not find anything relevant. In C++20, is there a new kind of compiler-generated constructor for structs?

答案1

得分: 11

这是p0960r3,允许从带括号的值列表进行聚合初始化。structclass通常是一个误导:您的原始struct Test类是一个聚合,但当您将其成员更改为私有访问规则时,它不再是聚合。聚合和聚合初始化的规则因语言的演变而不断变化,详细信息请参见The Fickle Aggregate

我尝试过谷歌搜索,但找不到相关信息。

如果您发现了给定语言版本的新功能,但不明白它是如何引入的或为什么引入的,可以查看open-std delta页面,这可能是一个好的起点:

C++17和C++20 DIS之间的更改

[...]

(P0960R3, P1975R0) 从带括号的列表进行聚合初始化

现在可以使用圆括号而不是花括号对聚合进行初始化:struct T { int a, b, c; }; T x(1, 2);一个(激发的)结果是,make_unique和emplace现在可以用于聚合类型。

英文:

This is p0960r3, which allows aggregate initialization from a parenthized list of values. struct or class is (as typically) a red herring here: your original struct Test class is an aggregate, but when you change its members to fall under private access rules it is no longer an aggregate. The rules for aggregates and aggregate initialization are notoriously ever-changing as the language evolves, see e.g. The Fickle Aggregate for details.

> I tried googling, but could not find anything relevant.

If you find a new feature of a given language version, and you do not understand how or why it was introduced, the open-std delta pages can be a good place to start:

> ### Changes between C++17 and C++20 DIS
>
> [...]
>
> (P0960R3, P1975R0) Aggregate initialization from a parenthesized list
>
> Aggregates can now be initialized with round parentheses instead of curly braces: struct T { int a, b, c; }; T x(1, 2); A (motivating) consequence is that make_unique and emplace now work with aggregate types.

huangapple
  • 本文由 发表于 2023年5月26日 00:12:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定