Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this two rvalue references examples have different behavior?

First example

int a = 0;
auto && b = ++a;
++a;
cout << a << b << endl;

prints 22

Second example

int a = 0;
auto && b = a++;
++a;
cout << a << b << endl;

prints 20

Question: Why in first example ++a in 3rd line also increments b, and why there is no such behavior in second example?

Update: New question arised.

like image 759
vladon Avatar asked Feb 10 '16 12:02

vladon


People also ask

What is an R value reference why might it be useful?

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.

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.

Can you modify an rvalue?

rvalue of User Defined Data type can be modified. But it can be modified in same expression using its own member functions only.

Is an rvalue reference an rvalue?

An rvalue reference is formed by placing an && after some type. An rvalue reference behaves just like an lvalue reference except that it can bind to a temporary (an rvalue), whereas you can not bind a (non const) lvalue reference to an rvalue.


1 Answers

Because pre-increment (++a) first increments the value of a, stores the result, and then returns the reference to a. Now a and b effectively point to the same object.

Post-increment (a++), however, first stores the current value of a in a temporary, increments a, and returns this temporary - to which your rvalue ref points. a and b point to different objects, more specifically - b is a temporary holding the value of a prior to incrementing.

This is the reason why it's encouraged to use ++it over it++ for iterators and other complex objects that define increment / decrement: the latter creates a temporary copy and thus may be slower.

like image 110
Violet Giraffe Avatar answered Nov 04 '22 07:11

Violet Giraffe