[英]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? C ++ 11标准中的哪个子句可以让我在下面的A::operator-()
中的return
语句中消除A
? In other words, if I replace the expression return A{-ai, -aj};
换句话说,如果我替换表达式,则return A{-ai, -aj};
by return {-ai, -aj};
通过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 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. 带有括号初始化列表的return语句通过从指定的初始化列表中进行复制列表初始化(8.5.4)初始化要从函数返回的对象或引用。 [ 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 在C ++标准的8.5.4节的列表初始化的第3段中对此进行了描述。
— Otherwise, if T is a class type, constructors are considered. —否则,如果T是类类型,则考虑构造函数。 The applicable constructors are enumerated and the best one is chosen through overload resolution (13.3, 13.3.1.7). 列举了适用的构造函数,并通过重载决议(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.