【发布时间】:2016-12-20 08:29:00
【问题描述】:
#include<iostream>
using namespace std;
struct B{};
struct A
{
A(const B &)
{
cout<<"A(const B &)"<<endl;
}
A(B &&)
{
cout<<"A(B &&)"<<endl;
}
};
A get()
{
B b;
return b;
}
int main()
{
get();
}
我用VC++14.2和GCC 5.4.0测试了代码,都输出了:
A(B &&)
为什么没有输出
A(const B &)
?
这段代码和copy elision有关系吗? (但是A和B是不同的类型,所以copy elision在这里应该不行)
【问题讨论】:
-
这其实是一个很有趣的问题。我发现 12.8/32 中的措辞有些不清楚:返回表达式的类型是否必须与函数的返回类型相同才能应用规则,这一点尚不清楚。我认为您可以将其视为 any 返回的具有自动存储的对象被视为由右值指定。不同的编译器think differently about this.
-
CWG1579 似乎与此相关。
-
@KerrekSB 根据 (31.1),
when the expression is the name of a non-volatile automatic object (other than a function parameter or a variable introduced by the exception-declaration of a handler (15.3)) with the same type (ignoring cv-qualification) as the function return type,我认为same type必须与return type完全相同。这意味着如果我返回A对象,copy elision将起作用。但是从B到A的隐式转换发生在copy elision之前,copy elision不应影响implicit conversion。 -
这不是问题,但不要使用
std::endl,除非您需要它的额外功能。'\n'结束一行。
标签: c++ return implicit-conversion