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.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· 为DeepSeek添加本地知识库
· 精选4款基于.NET开源、功能强大的通讯调试工具
· DeepSeek智能编程
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~