Why `copy constructor` is used while `move constructor` has been removed?

Viewed 651

As the subject,the related code is:

#include <iostream>     

class ABC     
{  public:  
    ABC() 
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(const ABC& a) 
    {
        std::cout << "copy construction" << std::endl;
    } 

    ABC(const ABC&& a) 
    {
        std::cout << "move construction" << std::endl;
    }
};                         

int main()   
{  
   ABC c1 = ABC();  

   return 0;  
}

Output with -fno-elide-constructors -std=c++11

default construction
move construction

If i remove the move constructor above, then the output is:

default construction
copy construction

why copy construction could be used while move constructor has been removed?You see, if there is a user defined move constructor, the compiler prefer to use move constructor.

As per some documentation,compiler provides a default move constructor.**So why don't the compiler use the default move constructor? I am a novice in C++.I would be grateful to have some help with this question.

1 Answers

As per some documentation,compiler provides a default move constructor.

Let's take a look at some documentation. The following is from cppreference.com.

If [conditions] then the compiler will declare a move constructor as a non-explicit inline public member of its class with the signature T::T(T&&).

You're right. The compiler does provide a defualt move constructor under the right conditions. However, those conditions are important. The first condition you seem to be aware of: there cannot be a user-defined move constructor. So that just leaves this list of conditions:

  • there are no user-declared copy constructors;
  • there are no user-declared copy assignment operators;
  • there are no user-declared move assignment operators;
  • there is no user-declared destructor;

And there you go. Your user-defined copy constructor is preventing the compiler from providing a default move constructor. Hence there is no move constructor to use.

Related