C++20 指定初始化器

发布于:2025-03-20 ⋅ 阅读:(16) ⋅ 点赞:(0)

指定初始化器

对于聚合,C++20 提供了一种方法来指定应该用传递的初始值初始化哪个成员,但只能使用它
来跳过参数。
假设有以下聚合类型:

struct Value 
{
     double amount{0};
     int precision{2};
     std::string unit{"Dollar";};
};

那么,现在支持以下方式来初始化该类型的值:

Value v1{100}; // OK (not designated initializers)
Value v2{.amount = 100, .unit = "Euro"}; // OK (second member has default value)
Value v3{.precision = 8, .unit = "$"}; // OK (first member has default value)

完整的示例请参见lang/designated.cpp。
注意以下限制:

  1. 必须使用= 或{} 传递初始值。
  2. 可以跳过会员,但必须遵循其顺序。按名称初始化的成员的顺序必须与声明中的顺序匹配。
  3. 必须对所有参数使用指定初始化式,或者不使用指定初始化式。不允许混合初始化。
  4. 不支持对数组使用指定初始化。
  5. 可以使用指定初始化式嵌套初始化,但不能直接使用.mem.mem。
  6. 初始化带有圆括号的聚合时,不能使用指定初始化器。
  7. 指定初始化式也可以用在联合体中。

例如:

Value v4{100, .unit = "Euro"}; // ERROR: all or none designated
Value v5{.unit = "$", .amount = 20}; // ERROR: invalid order
Value v6(.amount = 29.9, .unit = "Euro"); // ERROR: only supported for curly braces
#include <iostream>
#include <string>
 
struct Value{
    double amount = 0.0;
    int precision = 2;
    std::string unit = "Dollor";
};

int main(void)
{
    //until C++20
    Value v{};
    v.unit = "euro";
    
    //since C++20
    Value v1{100}; // OK (not designated initializers)
    Value v2{.amount = 100, .unit{"Euro"}}; // OK (second member has default value)
    Value v3{.precision{8}, .unit = "$"}; // OK (first member has default value)
    //Value v4{100, .unit = "Euro"}; // ERROR: all or none designated
    //Value v5{.unit = "$", .amount = 20}; // ERROR: invalid order
    //Value v6(.amount = 29.9, .unit = "Euro"); // ERROR: only supported for curly braces

}

 与编程语言C 相比,指定初始化器遵循成员顺序的限制,可以用于所有参数,也可以不用于参
数,不支持直接嵌套,不支持数组。尊重成员顺序的原因是确保初始化反映了调用构造函数的顺序
(与调用析构函数的顺序相反)。

作为使用=、{} 和联合体嵌套初始化的示例:

struct Sub 
{
    double x = 0;
    int y = 0;
};
      
struct Data 
{
     std::string name;
     Sub val;
};

不能直接嵌套指定初始化式:

Data d2{.val.y = 42}; // ERROR

 用圆括号聚合初始化


假设已经声明了以下集合:

struct Aggr 
{
     std::string msg;
     int val;
};


C++20 之前,只能使用花括号来初始化带有值的聚合:

Aggr a0; // OK, but no initialization

Aggr a1{}; // OK, value initialized with "" and 0

Aggr a2{"hi"}; // OK, initialized with "hi" and 0

Aggr a3{"hi", 42}; // OK, initialized with "hi" and 42

Aggr a4 = {}; // OK, initialized with "" and 0

Aggr a5 = {"hi"}; // OK, initialized with "hi" and 0

Aggr a6 = {"hi", 42}; // OK, initialized with "hi" and 42


自C++20 起,还可以使用圆括号作为外部字符来直接初始化,不带=:

Aggr a7("hi"); // OK since C++20: initialized with "hi" and 0
Aggr a8("hi", 42); // OK since C++20: initialized with "hi" and 42
Aggr a9({"hi", 42}); // OK since C++20: initialized with "hi" and 42


使用= 或内括号仍然不起作用:

Aggr a10 = "hi"; // ERROR
Aggr a11 = ("hi", 42); // ERROR
Aggr a12(("hi", 42)); // ERROR


使用内括号甚至可以编译,其用作使用逗号操作符的表达式周围的圆括号。
现在可以使用圆括号来初始化边界未知的数组:

int a1[]{1, 2, 3}; // OK since C++11
int a2[](1, 2, 3); // OK since C++20
int a3[] = {1, 2, 3}; // OK
int a4[] = (1, 2, 3); // still ERROR

然而,不支持” 省略大括号”(没有嵌套的大括号可以省略):

struct Arr 
{
    int elem[10];
};

Arr arr1{1, 2, 3}; // OK
Arr arr2(1, 2, 3); // ERROR
Arr arr3{{1, 2, 3}}; // OK
Arr arr4({1, 2, 3}); // OK (even before C++20)

要初始化std::arrays,仍须使用大括号:

std::array<int,3> a1{1, 2, 3}; // OK: shortcut for std::array{{1, 2, 3}}
std::array<int,3> a2(1, 2, 3); // still ERROR

用圆括号初始化聚合的原因
支持带圆括号的聚合初始化的原因是,可以用圆括号调用new 操作符:

struct Aggr 
{
    std::string msg;
    int val;
};

auto p1 = new Aggr{"Rome", 200}; // OK since C++11
auto p2 = new Aggr("Rome", 200); // OK since C++20 (ERROR before C++20)

这有助于支持在类型中使用聚合,这些类型在内部调用new 时使用括号将值存储在现有内存
中,就像容器和智能指针的情况一样。自C++20 起,以下是可能的情况:
• 现在可以对聚合使用std::make_unique<>() 和std::make_shared<>():

auto up = std::make_unique<Aggr>("Rome", 200); // OK since C++20
auto sp = std::make_shared<Aggr>("Rome", 200); // OK since C++20

C++20 之前,无法对聚合使用这些辅助函数。
• 现在可以将新值放置到聚合容器中:

std::vector<Aggr> cont;
cont.emplace_back("Rome", 200); // OK since C++20

仍然有一些类型不能用括号初始化,但可以用花括号初始化: 作用域枚举(枚举类类型)。类型
std::byte (C++17 引入) 就是一个例子:

std::byte b1{0}; // OK
std::byte b2(0); // still ERROR
auto upb2 = std::make_unique<std::byte>(0); // still ERROR
auto upb3 = std::make_unique<std::byte>(std::byte{0}); // OK

对于std::array,仍然需要大括号(如上所述):

 std::vector<std::array<int, 3>> ca;
 ca.emplace_back(1, 2, 3); // ERROR
 ca.emplace_back({1, 2, 3}); // ERROR
 ca.push_back({1, 2, 3}); // still OK

详细地用圆括号聚合初始化
引入圆括号初始化的建议列出了以下设计准则:
• Type(val) 的现有含义都不应该改变。
• 括号初始化和括号初始化应尽可能相似,但也应尽可能不同,以符合现有的括号列表和括号
列表的模型。
实际上,带花括号的聚合初始化和带圆括号的聚合初始化有以下区别:
• 带圆括号的初始化不会检测窄化转换。
• 用圆括号初始化允许所有隐式转换(不仅是从派生类到基类)。
• 当使用括号时,引用成员不会延长传递的临时对象的生命周期.
• 使用圆括号不支持大括号省略(使用它们就像向形参传递实参一样)。
• 带空括号的初始化甚至适用于显式成员。
• 使用圆括号不支持指定初始化式。


缺少检测窄化的例子如下:

struct Aggr 
{
    std::string msg;
    int val;
};

Aggr a1{"hi", 1.9}; // ERROR: narrowing
Aggr a2("hi", 1.9); // OK, but initializes with 1

std::vector<Aggr> cont;
cont.emplace_back("Rome", 1.9); // initializes with 1

emplace 函数永远不会检测窄化。
处理隐式转换时的区别示例如下:

//example of the difference when dealing with implicit conversions is this:
struct Other {
...
operator Aggr(); // defines implicit conversion to Aggr
};

Other o;
Aggr a7{o}; // ERROR: no implicit conversion supported
Aggr a8(o); // OK, implicit conversion possible

聚合本身不能定义转换,因为聚合不能有用户定义的构造函数。
缺少大括号省略和大括号初始化的复杂规则,会导致以下行为:

Aggr a01{"x", 65}; // init string with "x" and int with 65
Aggr a02("x", 65); // OK since C++20 (same effect)

Aggr a11{{"x", 65}}; // runtime ERROR: "x" doesn’t have 65 characters
Aggr a12({"x", 65}); // OK even before C++20: init string with "x" and int with 65

Aggr a21{{{"x", 65}}}; // ERROR: cannot initialize string with initializer list of
,→ "x" and 65
Aggr a22({{"x", 65}}); // runtime ERROR: "x" doesn’t have 65 characters

 Aggr a31{'x', 65}; // ERROR: cannot initialize string with ’x’
 Aggr a32('x', 65); // ERROR: cannot initialize string with ’x’

 Aggr a41{{'x', 65}}; // init string with ’x’ and char(65)
 Aggr a42({'x', 65}); // OK since C++20 (same effect)

 Aggr a51{{{'x', 65}}}; // init string with ’x’ and char(65)
 Aggr a52({{'x', 65}}); // OK even before C++20: init string with ’x’ and 65

 Aggr a61{{{{'x', 65}}}}; // ERROR
 Aggr a62({{{'x', 65}}}); // OK even before C++20: init string with ’x’ and 65

当执行复制初始化(用= 初始化) 时,显式很重要,使用空括号可能会产生不同的效果:

struct C 
{
     explicit C() = default;
};

struct A  // aggregate
{
    int i;
    C c;
};

auto a1 = A{42, C{}}; // OK: explicit initialization
auto a2 = A(42, C()); // OK since C++20: explicit initialization

auto a3 = A{42}; // ERROR: cannot call explicit constructor
auto a4 = A(42); // ERROR: cannot call explicit constructor

auto a5 = A{}; // ERROR: cannot call explicit constructor
auto a6 = A(); // OK: can call explicit constructor

这在C++20 中并不新鲜,在C++20 之前就已经支持a6 的初始化了。
最后,若对具有右值引用成员的聚合使用圆括号进行初始化,则初始值的生存期不会延长,所
以不应该传递临时对象(右值):

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

int f();
int n = 10;

A a1{1, f()}; // OK, lifetime is extended
std::cout << a1.r << '\n'; // OK
A a2(1, f()); // OOPS: dangling reference
std::cout << a2.r << '\n'; // runtime ERROR
A a3(1, std::move(n)); // OK as long as a3 is used only while n exists
std::cout << a3.r << '\n'; // OK
#include <iostream>
#include <string>
#include <memory>

struct Widget{
    Widget() { std::cout << "ctor" << std::endl;
    str = std::make_unique<std::string>("test:temporary do not extend rvalue reference member lifetime");}

    ~Widget(){std::cout << "dtor" << std::endl; str.reset();}

    friend std::ostream& operator << (std::ostream& os, const Widget& w){ return os << *(w.str);}
private:
    std::unique_ptr<std::string> str{};
};
struct A {
     int a;
     Widget&& r;
};

Widget f() { return Widget{};}

void test_rvalue_ref_mem(){
	Widget n{};

	A a1{1, f()}; // OK, lifetime is extended
    std::cout << a1.r << std::endl; // OK

    A a3(1, std::move(n)); // OK as long as a3 is used only while n exists
    std::cout << a3.r << std::endl; // OK
}
void test_temporary_if_extend_rvalue_reference_member_lifetime()
{
	std::cout << "----------------------------" << std::endl;
    A a2(1, f()); // OOPS: dangling reference
    std::cout << "----------------------------" << std::endl;
    std::cout << a2.r << std::endl; // runtime ERROR
    std::cout << "bug! bug! it is too bad!" << std::endl;
}
int main()
{
	test_rvalue_ref_mem();
	test_temporary_if_extend_rvalue_reference_member_lifetime();

    return 0;
}

由于这些复杂的规则和陷阱,只有在必要时才应该使用带圆括号的聚合初始化,比如在使用
std::make_unique<>()、std::make_shared<>() 或emplace 函数时。