为什么不调用移动构造函数? [英] Why is the move constructor not called?
问题描述
根据我的理解,移动构造函数将在创建临时对象时被调用。这里的 getA()
函数返回一个临时对象,但我的程序不打印来自move构造函数的消息:
As per my understanding, the move constructor will be called when there is a temporary object created. Here the getA()
function is returning a temporary object but my program is not printing the message from the move constructor:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"Hi from default\n";
}
A(A && obj)
{
cout<<"Hi from move\n";
}
};
A getA()
{
A obj;
cout<<"from getA\n";
return obj;
}
int main()
{
A b(getA());
return 0;
}
推荐答案
输出实例 obj
,并将对象直接发送回调用者,而不进行概念值复制。
The compiler is allowed to optimise out the instance obj
and send the object directly back to the caller without a conceptual value copy being taken.
称为命名返回值优化(NRVO)。这是一个比传统的返回值优化(RVO)更积极的优化,编译器可以调用它来避免匿名临时值的副本。
This is called named return value optimisation (NRVO). It's a more aggressive optimisation than classical return value optimisation (RVO) that a compiler can invoke to obviate the value copy of an anonymous temporary.
为了避免疑问,编译器可以这样做,即使有这样做的副作用(在您的情况下缺乏控制台输出)。
For the avoidance of doubt the compiler can do this even if there is a side-effect in doing so (in your case the lack of console output).
这篇关于为什么不调用移动构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!