Pitfalls: C++ 中的index运算符

名可名, 非常名

在调一个题目的过程中发现了一个之前从未意识到的问题.

考虑如下代码

vector<int> a;

int f(int x){
    a.push_back(x);
    return *a.rbegin();
}

a.push_back(0);
a[0]=f(1);

试问最后a[0]的值.

Unique Variable

a variable provides us with named storage that our programs can manipulate.

这里需要指出的是, a[0]是一个返回lvalue的expression, 它是一个variable, 但并是一个unique variable.
(unique variable这个词是我造的, 下面将会解释其含义)

如果一个变量在它的lifetime中都指向 (refer to) 同一storage, 则称其为 unique variable.

Remember That Operands Can Be Evaluated in Any Order

Precedence specifies how the operands are grouped. It says nothing about the order in which the operands are evaluated. In most cases, the order is largely unspecified. In the following expression

int i = f1() * f2();

We know that f1 and f2 must be called before the multiplication can be done. After all, it is their results that are multiplied. However, we have no way of knowing whether f1 will be called before f2 or vice versa.

For operators that do not specify evaluation order, it is an error for an expression to refer to and change the same object. Expressions that do so have undefined behavior.

There are four operators that do guarantee the order in which operands are evaluated: the logical AND (&&) operator, the logical OR (||) operator, the conditional (?:) operator and the comma (,) operators.

转载于:https://www.cnblogs.com/Patt/p/6127876.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值