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.
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.
“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.
rvalue of User Defined Data type can be modified. But it can be modified in same expression using its own member functions only.
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.
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.
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