简体   繁体   中英

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

What clause in the C++11 Standard does allow me to eliminate the A in the return statement in the A::operator-() below? In other words, if I replace the expression return A{-ai, -aj}; by return {-ai, -aj}; the code compiles and executes correctly. I'd like to know how does that work, using the Standard, if possible?

#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

A return statement with a braced-init-list initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list. [ Example:

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

— end example ]

This is described in paragraph #3 of section 8.5.4 List-initialization of the C++ Standard

— Otherwise, if T is a class type, constructors are considered. The applicable constructors are enumerated and the best one is chosen through overload resolution (13.3, 13.3.1.7). If a narrowing conversion (see below) is required to convert any of the arguments, the program is ill-formed.

End below there is an example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM