pretty

Friday 22 May 2015

std::move overload resolution


#include 
class A
{
public:
  A(){}
  A(A& other) { std::cout << "copy ctor" << std::endl; }
  A(const A& other) { std::cout << "const copy ctor" << std::endl; }
  A(A&& other) { std::cout << "move ctor" << std::endl; }
};

class B
{
public:
  B(){}
  B(B& other) { std::cout << "copy ctor" << std::endl; }
  B(const B& other) { std::cout << "const copy ctor" << std::endl; }
};

class C
{
public:
  C(){}
  C(C& other) { std::cout << "copy ctor" << std::endl; }
};

int main()
{
  A a1;
  A a2(std::move(a1)); // move ctor called
  
  B b1;
  B b2(std::move(b1)); // const copy ctor called
  
  C c1;
  // C c2(std::move(c1)); // compile-time error: no matching constructor for initialization of 'C'

  return 0;
}
    C c1;
    const C &c2 = std::move(c1); // OK: const reference can bind to rvalue
    C && c3 = std::move(c1); // OK: rvalue reference
    // C &c4 = std::move(c1); // Error: Non-const reference cannot bind to rvalue
    // C c5 = std::move(c1); // Error: No move constructor or const copy constructor in C
Quote: "Rvalue references can be used to extend the lifetime of a modifiable temporary (note, lvalue references to const can extend lifetimes too, but they are not modifiable)"

No comments :

Post a Comment