Search code examples
c++move-constructor

C++ : Why is move constructor not getting called?


I am experimenting with the following code :

#include <iostream>
#include <utility>
using namespace std;

class A
{
    int data;
public:
   A(): data{0}
   {

   }

   A(const A& other)
   {
       print(other);
   }


   A(A&& other)
   {
       print(other);
   }

   void print(const A& other) const
   {
      cout << "In print 1" << endl;
   }

   void print(const A&& other) const
   {
      cout << "In print 2" << endl;
   }

};


int main() {
    A a0;
    A a1(a0);
    A a2(A());

    return 0;
}

I was expecting the output to be :

In print 1
In print 1

However, the actual output is :

In print 1

Clearly, the move constructor is not getting called. Why so? And what is getting called in its place during construction of a2?


Solution

  • Because A a2(A()); is actually function declaration, not a declaration of an object. See this:

    My attempt at value initialization is interpreted as a function declaration, and why doesn't A a(()); solve it?

    If you want to see the move constructor, do something like this:

    A a2((std::move(A())));