0

I just made a function that takes a rvalue reference as parameter but if i pass '67', it works but let's say that "int&& ref = 67", if i pass ref as parameter it throws error.

#include <iostream>
using namespace std;

void func(int&& a){
    std::cout << a << " from rvalue" << std::endl;
}


int main(){
    int&& ref = 6;
    //func(ref); // error
    func(6); // holds good
    return 0;
}

// error -> cannot bind rvalue reference of type 'int&&' to lvalue of type 'int'

I dont know why is it saying lvalue of type 'int' even argument is of type 'int&&'(rvalue not lvalue) help me out what's the problem. Thanks in Advance...............

1 Answers1

3

Within this call:

//func(ref); // error

ref is an lvalue (because it has a name) and not rvalue reference.

For make it to rvalue use move:

  func(move(ref)); // this will cast ref to rvalue

Dont get confused with && (not everything having && in front of it is a rvalue):

func(int&& x) 
// && means here: you can call func() only with those expressions which can bind to rvalue (like numeric constants for ex.)
// here you allow constructing x only from rvalues
{
BUT: (here it doesnt matter any more how x got constructed)
... for every usage of x within this scope: x is lvalue (because it has a name)
StPiere
  • 4,113
  • 15
  • 24
  • OK. But what if i overload this function with func(int a); and invoke it as func(std::move(ref)); –  Sep 11 '20 at 11:03
  • 1
    It's perfectly fine, because both of these are valid: int a = b; and int a = 6; For regular types (int's, floats, etc.) a = move(b) will just copy. move() gets only interesting in cases where you have types owning some resources, for ex. strings, vectors, etc. – StPiere Sep 11 '20 at 11:04