英文:
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 <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?
答案1
得分: 11
这是p0960r3,允许从带括号的值列表进行聚合初始化。struct
或class
通常是一个误导:您的原始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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论