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?
An address can not be taken of rvalues. An rvalue has no name as its a temporary value.
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.
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.
“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.
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 tocv2 T2
” if “cv2 T2
” is reference-compatible with “cv1 T1
”.
A temporary will be created if for example you call foo(1);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With