Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing int&& to f(int&&)

Tags:

What is exactly happening here? Why is this an error?

void f(int &&);

int && i = 5;

f(i);

Isn't it a bit counterintuitive?

I would expect i to be a rvalue reference, and so be able to pass it to f(). But I get an error;

no known conversion from int to int &&

So I guess i is not an rvalue reference after declaration?

like image 754
Jorge González Lorenzo Avatar asked Feb 10 '16 11:02

Jorge González Lorenzo


People also ask

Is Integer same as int?

A int is a data type that stores 32 bit signed two's compliment integer. On other hand Integer is a wrapper class which wraps a primitive type int into an object. int helps in storing integer value into memory. Integer helps in converting int into object and to convert an object into int as per requirement.

Is Java Integer a reference type?

Java Type System Java has a two-fold type system consisting of primitives such as int, boolean and reference types such as Integer, Boolean. Every primitive type corresponds to a reference type. Every object contains a single value of the corresponding primitive type.

What is Integer parameter?

Integer parameters define integer values that are used as inputs for some LiveCompare actions.


1 Answers

I see why you are confused. The thing to remember is that whenever you have a variable name, you have an l-value.

So when you say:

int i = 0; // lvalue (has a name i)

And also

int&& i = 0; // lvalue (has a name i)

So what is the difference?

The int&& can only bind to an r-value so:

int n = 0;
int i = n; // legal

BUT

int n = 0;
int&& i = n; // BAD!! n is not an r-value

However

int&& i = 5; // GOOD!! 5 is an r-value

So when passing i to f() in this example you are passing an l-value, not an r-value:

void f(int &&);

int&& i = 5; // i is an l-value

f(i); // won't accept l-value

The situation is actually a little more complicated than I have presented here. If you are interested in a fuller explanation then this reference is quite thorough: http://en.cppreference.com/w/cpp/language/value_category

like image 68
Galik Avatar answered Nov 24 '22 09:11

Galik