Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the move constructor not called? [duplicate]

Tags:

c++

c++11

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;
}
like image 642
Gilson PJ Avatar asked Jul 07 '16 13:07

Gilson PJ


People also ask

What is the difference between a move constructor and a copy constructor?

If any constructor is being called, it means a new object is being created in memory. So, the only difference between a copy constructor and a move constructor is whether the source object that is passed to the constructor will have its member fields copied or moved into the new object.

Is move constructor automatically generated?

If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then: No move constructor is automatically generated. No move-assignment operator is automatically generated.

Why is copy constructor called reference?

A copy constructor defines what copying means,So if we pass an object only (we will be passing the copy of that object) but to create the copy we will need a copy constructor, Hence it leads to infinite recursion. So, A copy constructor must have a reference as an argument.

What is move constructor CPP?

A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying.


1 Answers

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

like image 52
Bathsheba Avatar answered Sep 23 '22 03:09

Bathsheba