在 C++ 中使用 initializer_list 进行结构赋值

struct assignment with initializer_list in c++

我有一个结构

struct Data {
   int a,b;
   Data& operator=(Data &&other) = delete;
};

现在当我调用赋值运算符时

Data A[2];
A[0] = {1, 2};

调用已删除的函数时出现编译错误。 我的问题是 initializer_list 如何转换为 Data 类型的右值引用?

My question is how does the initializer_list gets converted to a rvalue reference of type Data?

如果 initializer_list 是指类型 std::initializer_list,则您的示例中没有。您正在使用 list initialization to create a temporary Data instance (a prvalue,而不是右值引用)并将其分配给 A[0],这当然会失败,因为移动赋值运算符已被删除。

您的示例与

相同
A[0] = Data{1, 2};

C++17 涵盖了此语法 [expr.ass]/9:

A braced-init-list may appear on the right-hand side of

  • [...]
  • an assignment to an object of class type, in which case the initializer list is passed as the argument to the assignment operator function selected by overload resolution.

举个例子:

z = { 1,2 }; // meaning z.operator=({1,2})

braced-init-list 作为函数参数的行为意味着函数参数由该列表初始化。在这种情况下 Data&& other{1, 2} 初始化。 [dcl.init.list]/3.4:

Otherwise, if T is a reference type, a prvalue of the type referenced by T is generated. The prvalue initializes its result object by copy-list-initialization or direct-list-initialization, depending on the kind of initialization for the reference. The prvalue is then used to direct-initialize the reference.

所以有一个 Data 类型的纯右值由 {1, 2} 初始化,它成为 operator=.

参数的初始化器