Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce a calling of a moving constructor (C++)?

I have this couple of code-lines:

#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 output:

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

What need I to do in order to the A::A(A&&) will be called from the B::B(A&&)?

As you can see adding noexcept does not solve this issue.

like image 514
Serge Roussak Avatar asked Feb 10 '23 04:02

Serge Roussak


1 Answers

Although the type of a is an rvalue reference to A, a itself is an lvalue. To retain its rvalue-ness, you need to use std::move:

B(A&& a) noexcept :
  _a(std::move(a))
{}
like image 97
TartanLlama Avatar answered Feb 23 '23 02:02

TartanLlama