c++ - C++20 中的新型自动生成构造函数

下面的代码不能在使用 -std=c++17 的 GCC 11 上编译,但可以使用 -std=c++20:

#include <iostream>
#include <string>

struct Foo {
    std::string s;
    int i;
};

int main()
{
    Foo foo("hello", 42);
    std::cout << foo.s << ' ' << foo.i << '\n';
}

C++20 中有什么功能可以实现这一点?编译器生成什么样的构造函数?

最佳答案

这里使用的 C++20 特性是 initialization of aggregates from parenthesis (P0960R3) :

This paper proposes allowing initializing aggregates from a parenthesized list of values; that is, Aggr(val1, val2) would mean the same thing as Aggr{val1, val2}, except that narrowing conversions are allowed.

这是来自上面链接的示例:

struct A {
  int a;
  int&& r;
};

int f();
int n = 10;

A a1{1, f()};               // OK, lifetime is extended
A a2(1, f());               // well-formed, but dangling reference
A a3{1.0, 1};               // error: narrowing conversion
A a4(1.0, 1);               // well-formed, but dangling reference
A a5(1.0, std::move(n));    // OK

因此,为了使您的代码适用于 C++17,只需将圆括号替换为大括号即可。

#include <iostream>
#include <string>

struct Foo {
    std::string s;
    int i;
};

int main()
{
    Foo foo{"hello", 42};
    std::cout << foo.s << ' ' << foo.i << '\n';
}

https://stackoverflow.com/questions/69331785/

相关文章:

python - 如何减少由许多条件语句组成的函数?

php - 无法加载 Mac M1 SQL Server SQLSrv OpenSSL 库,请确保已

javascript - 在javascript中找到嵌套数组中的最低值

r - 如果 R 中的其他列中存在值,则用于创建 T/F 列的 dplyr 解决方案

node.js - Docker + WebGL + Headless Chrome 错误 : Pa

php - Shopware 6 价格收集器/处理器的折扣计算错误

javascript - 正则表达式获取第一次和最后一次出现之间的子字符串

visual-studio - 缺少 Visual Studio 性能探查器

python - 如何根据最大值将字典中的所有值分配给变量

c# - 从 C# 中的 Win32_PnPEntity 获取 DEVPKEY_Device_Bus