Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind rvalue reference to lvalue with `void*`

Tags:

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; 
like image 576
Nick Avatar asked Apr 20 '18 07:04

Nick


People also ask

Can lvalue bind to rvalue reference?

An lvalue reference can bind to an lvalue, but not to an rvalue.

Is an rvalue reference an lvalue?

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.

How do you pass rvalue reference to a function?

If you want pass parameter as rvalue reference,use std::move() or just pass rvalue to your function.

What is the use of rvalue reference?

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.


1 Answers

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 
like image 65
songyuanyao Avatar answered Oct 15 '22 19:10

songyuanyao