While trying to understand how rvalue references work I ended up with this piece of code:
int* iptr = nullptr; int*&& irr = iptr;
Compiling the above code gives the following error:
error: rvalue reference to type 'int *' cannot bind to lvalue of type 'int *'
I understand this is correct, but why does the following code, where I bind using a void*
instead of int*
, compiles without any problem? Will the runtime behavior be correct or should I expect undefined behavior?
int* iptr = nullptr; void*&& irr = iptr;
An lvalue reference can bind to an lvalue, but not to an rvalue.
An lvalue is an expression that yields an object reference, such as a variable name, an array subscript reference, a dereferenced pointer, or a function call that returns a reference. An lvalue always has a defined region of storage, so you can take its address. An rvalue is an expression that is not an lvalue.
If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.
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.
This is well-formed.
int*
and void*
are different types; you can't bind a int*
to reference to void*
directly. The int*
needs to be converted to void*
firstly, which is a temporary object and could be bound to rvalue-reference. (PS the lifetime of the temporary is extended to the lifetime of the reference.)
Note that irr
doesn't bind to iptr
; so any modification on it has nothing to do with iptr
.
This is not special for void*
, same thing happens for other types, e.g.
char c; int&& r = c; // a temporary int is constructed from c and then bound to r; // its lifetime is extened to the lifetime of r
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