Pitfalls: C++ 中的index运算符

时间:2022-11-07 14:47:38

名可名, 非常名

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

考虑如下代码

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 (?