mercredi 1 juin 2016

Move semantics and constructors when dereferencing a new

I have the following code (http://ift.tt/1TWWKkz):

#include <iostream    

class A {
  public:
  explicit A(int a)         {std::cout << "Main constructor" << std::endl;}
  A(const A& a)             {std::cout << "Copy constructor" << std::endl;}
  A& operator =(const A& a) {std::cout << "Copy assignment" << std::endl; return *this;}
  A(A&& a)                  {std::cout << "Move constructor" << std::endl;}
  A& operator =(A&& a)      {std::cout << "Move assignemnt" << std::endl; return *this;}
};

int main(void) {
    std::cout << "\nA a3(A(0))" << std::endl;
    A a3(A(0));
    std::cout << "\nA a31(std::move(A(0)))" << std::endl;
    A a31(std::move(A(0)));
    std::cout << "\nA a4(*(new A(0)))" << std::endl;
    A a4(*(new A(0)));
    std::cout << "\nA a41(std::move(*(new A(0))))" << std::endl;
    A a41(std::move(*(new A(0))));
}

This code writes the following:

A a3(A(0))
Main constructor  

-> After having read Move semantics and copy constructor I assume RVO happened and a3 takes over the content of the construction of A(0).

A a31(std::move(A(0)))
Main constructor
Move constructor   

-> OK

A a4(*(new A(0)))
Main constructor
Copy constructor    

-> Why is not this a move constructor instead of the Copy constructor ?

A a41(std::move(*(new A(0))))
Main constructor
Move constructor  

-> OK

Aucun commentaire:

Enregistrer un commentaire