为什么这两个右值引用示例具有不同的行为? [英] Why this two rvalue references examples have different behavior?
问题描述
第一个例子
int a = 0;
auto && b = ++a;
++a;
cout << a << b << endl;
打印 22
第二个例子
int a = 0;
auto && b = a++;
++a;
cout << a << b << endl;
打印 20
问题:为什么在第一个例子中第三行的 ++a
也增加了 b
,为什么在第二个例子中没有这种行为?
Question:
Why in first example ++a
in 3rd line also increments b
, and why there is no such behavior in second example?
更新: 出现了新问题.
推荐答案
因为预增(++a
)先自增a
的值,存储结果,然后 then 返回对 a
的引用.现在 a
和 b
有效地指向同一个对象.
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.
后增量(a++
),然而,首先将a
的当前值存入一个临时的,自增a
,并返回这个临时 - 您的右值参考所指向的.a
和 b
指向不同的对象,更具体地说 - b
是临时保存 a
之前的值递增.
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.
这就是为什么鼓励对迭代器和其他定义递增/递减的复杂对象使用 ++it
而不是 it++
的原因:后者创建一个临时副本并因此可能会更慢.
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.
这篇关于为什么这两个右值引用示例具有不同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!