此代码不在VS2010中编译。它发出错误C2440:"argument":无法从"A"转换为"A&",但根据标准中的12.8p2,A::A(A&)
是有效的复制构造函数,a
是main()
中表达式A b = foo(a);
中的左值。
#include <iostream>
class A
{
public:
int x;
A(int a) { x = a; std::cout << "Constructorn"; }
A(A& other) { x = other.x; std::cout << "Copy ctorn"; }
A(A&& other) { x = other.x; other.x = 0; std::cout << "Move ctorn"; }
};
A foo(A a)
{
return a;
}
int main(void)
{
A a(5);
A b = foo(a);
}
我认为这取决于您所谈论的标准。假设C++11,那么我认为它应该是可以的,并且应该产生以下结果:
Constructor <- Construction of 'a' in main
Copy ctor <- Construction of 'a' in foo
Move ctor <- Move from foo's return value into b
正如您所指出的,传递到foo中的a是一个左值。然而,foo的返回值是一个右值,因此应该调用常量A&在C++11之前的情况下,复制构造函数(不存在),或在C++11的情况下移动构造函数。