2

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 ?

cigien
  • 57,834
  • 11
  • 73
  • 112
Talespin_Kit
  • 20,830
  • 29
  • 89
  • 135
  • 2
    Possible duplicate of [Overload resolution between object, rvalue reference, const reference](https://stackoverflow.com/questions/17961719/overload-resolution-between-object-rvalue-reference-const-reference) – Mat Oct 21 '19 at 05:55
  • Duplicate of answered: [Ambiguous call with overloaded r-value reference function](https://stackoverflow.com/questions/28701039/ambiguous-call-with-overloaded-r-value-reference-function/31551595) – MorJ Oct 21 '19 at 06:19
  • In the first ctor your reference becomes dangling, you know? – bipll Oct 22 '19 at 12:09

0 Answers0