class A
{
public:
A()
{
cout << "A()" << endl;
}
A(const A&)
{
cout << "A(const A&)" << endl;
}
A(A&&)
{
cout << "A(A&&)" << endl;
}
A& operator=(const A&)
{
cout << "A(const A&)" << endl;
}
A& operator=(A&&)
{
cout << "A(const A&&)" << endl;
}
~A()
{
cout << "~A()" << endl;
}
};
A&& f_1()
{
A a;
return static_cast<A&&>(a);
}
A f_2()
{
A a;
return static_cast<A&&>(a);
}
int main()
{
cout << "f_1:" << endl;
f_1();
cout << "f_2:" << endl;
f_2();
}
输出为:将一个函数声明为BigStruct && foo(...)是一个好习惯吗?
f_1:
A()
~A()
f_2:
A()
A(A&&)
~A()
~A()
示例代码明显表明,F_1()比F_2更有效()。
所以,我的问题是:
我们一定要声明一个功能some_return_type & & F(...);而不是some_return_type f(...); ?
如果回答我的问题是真实的,那么另一个问题如下:声明为some_return_type F(...)
已经有很多很多的功能;在C++世界中,我们是否应该将它们改为现代形式?
你用'-Wall'编译了它吗? “警告:引用局部变量'a'返回”。这是在你的'f_1'定义中... – mfontanini
http://stackoverflow.com/questions/4986673/c11-rvalues-and-move-semantics-confusion – Fanael