dimanche 20 octobre 2019

How to pass int as rvalue argument to a function or constructor?

In the following code the class A has 2 constructors, one taking int by value and the other taking int by rvalue reference. How to create an object using the second constructor call.

#include <iostream>
using namespace std;

class A
{
public:
  A(int i) : r_i(i)
  {
    cout<<endl<<"A(inti)";
  }

  A(int&& i) : r_i(i)
  {
    cout<<endl<<"A(int&&)";
  }

private:
  int &r_i;
};

int main()
{
  int j = 5;
  A a(j); // Works
  A b(std::move(j)); //  Error [1]
}

Error [1] : call of overloaded ‘A(std::remove_reference<int&>::type)’ is ambiguous

Which c++ rule prevents the call to rvalue constructor ?

Aucun commentaire:

Enregistrer un commentaire