How to ensure a call to a moving constructor (C ++)?

I have a couple of codes:

#include <iostream>

using namespace std;

class A
{
public:
  A() noexcept
  {
    cout << "A::A()" << endl;
  }
  A(const A&) noexcept
  {
    cout << "A::A(const A&)" << endl;
  }
  A(A&&) noexcept
  {
    cout << "A::A(A&&)" << endl;
  }
};

class B
{
public:

  B(const A& a) noexcept :
    _a(a)
  {}
  B(A&& a) noexcept :
    _a(a)
  {}

private:
  A _a;
};

int main(int argc, char* argv[])
{
  A a;
  B b1 = B(a);
  B b2 = B(A());
}

They produce this conclusion:

A::A()
A::A(const A&)
A::A()
A::A(const A&)

What do I need to do to get A::A(A&&)called from B::B(A&&)?

As you can see, adding noexceptdoes not solve this problem.

+4
source share
1 answer

Although the type ais an rvalue reference to a, aitself is an lvalue. To save it rvalue-ness, you need to use std::move:

B(A&& a) noexcept :
  _a(std::move(a))
{}
+9

All Articles