C++11 标准中的哪些条款允许我消除下面“A::operator-()”中“返回”语句中的“A”

What clause in the C++11 Standard does allow me to eliminate the `A` in the `return` statement in the `A::operator-()` below?

本文关键字:语句 operator- 返回 标准 C++11 允许我      更新时间:2023-10-16

C++11 标准中的哪个子句允许我消除下面A::operator-()return语句中的A?换句话说,如果我通过return {-a.i, -a.j};替换表达式return A{-a.i, -a.j};,代码将正确编译和执行。如果可能的话,我想知道使用标准是如何工作的?

#include <iostream>
struct A {
    int i;
    int j;
    A(int n, int m) : i(n), j(m) {}
};

A operator-(A a) { return A{-a.i, -a.j}; }
int main()
{
    A a(1, 2);
    A b = -a;
    std::cout << b.i << "  " << b.j << 'n';
}

6.6.3/2

带有大括号初始化列表的 return 语句通过指定初始值设定项的复制列表初始化 (8.5.4) 初始化要从函数返回的对象或引用 列表。[ 示例:

    std::pair<std::string,int> f(const char* p, int x) {
      return {p,x};
    }

— 结束示例 ]

这在第

8.5.4 节的段落 #3 中描述 C++ 标准的列表初始化

— 否则,如果 T 是类类型,则考虑构造函数。这 枚举适用的构造函数并选择最佳构造函数 通过重载解析(13.3、13.3.1.7)。如果变窄 转换(见下文)是转换任何参数所必需的, 程序格式不正确。

下面结束有一个例子

struct S {
// no initializer-list constructors
S(int, double, double); // #1
S(); // #2
// ...
};
S s1 = { 1, 2, 3.0 }; // OK: invoke #1
S s2 { 1.0, 2, 3 }; // error: narrowing
S s3 { }; // OK: invoke #2