Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to take the address of an rvalue reference?

Tags:

c++

c++11

c++14

Given

void foo( int&& x ) {

    std::cout << &x;
}

This works but what does this address actually represent? Is a temporary int created when foo is called and that is what the address represents? If this is true and if I write int y = 5; foo(static_cast<int&&>(y));, does this cause another temporary to be created or will the compiler intelligently refer to y?

like image 832
edaniels Avatar asked Oct 14 '14 23:10

edaniels


People also ask

Can you take the address of an rvalue?

An address can not be taken of rvalues. An rvalue has no name as its a temporary value.

What does rvalue reference mean?

Rvalue references is a small technical extension to the C++ language. Rvalue references allow programmers to avoid logically unnecessary copying and to provide perfect forwarding functions. They are primarily meant to aid in the design of higer performance and more robust libraries.

Where are rvalue references used?

R-value references as function parameters R-value references are more often used as function parameters. This is most useful for function overloads when you want to have different behavior for l-value and r-value arguments.

What is the difference between lvalue and rvalue references?

“l-value” refers to a memory location that identifies an object. “r-value” refers to the data value that is stored at some address in memory. References in C++ are nothing but the alternative to the already existing variable. They are declared using the '&' before the name of the variable.


1 Answers

When you take an address of an rvalue reference, it returns a pointer to the object that reference is bound to, like with lvalue references. The object can be a temporary or not (if for example you cast an lvalue to rvalue reference like you do in your code).

int y = 5; foo(static_cast<int&&>(y)); does not create a temporary. This conversion is described in part 5.2.9/3 of the standard:

A glvalue, class prvalue, or array prvalue of type “cv1 T1” can be cast to type “rvalue reference to cv2 T2” if “cv2 T2” is reference-compatible with “cv1 T1”.

A temporary will be created if for example you call foo(1);.

like image 120
Anton Savin Avatar answered Oct 05 '22 01:10

Anton Savin