Why is the move constructor not called? [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-23 07:38:46

问题


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;
}

回答1:


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.

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).



来源:https://stackoverflow.com/questions/38246823/why-is-the-move-constructor-not-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!