gpt4 book ai didi

C++移位运算符优先级怪异

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:52:51 25 4
gpt4 key购买 nike

考虑以下代码:

typedef vector<int> intVec;

intVec& operator<<(intVec& dst, const int i) {
dst.push_back(i);
return dst;
}
int intResult0() {
return 23;
}
int intResult1() {
return 42;
}

// main
intVec v;
v << intResult0() << intResult1();

奇怪的是,编译器生成的代码会评估 intResult1 BEFORE intResult0(使用最新的 VC 和 gcc 测试)。为什么编译器会这样做?通过这样做,评估和使用各个值之间的时间(不必要地)增加(?),即首先获取 42,但最后推送到 vector 。C++ 标准是否规定了这一点?

最佳答案

两个序列点之间的子表达式求值顺序未定义。

上面的代码是语法糖:

v.operator<<(intResult0()).operator<<(intResult1());

编译器的唯一约束是它必须在调用方法之前评估所有参数并遵守优先规则。但只要遵循这些规则,每个实现都可以选择细节,因此这个顺序可能会在编译器之间发生变化。

在这个例子中:

  • 所以在 intResult2() 之前调用 intResult1() 是完全合法的。
  • 但是 intResult0() 必须在调用 operator<<() 之前调用(左)
  • 和 intResult1() 必须在调用 operator<<() 之前调用(右)
  • 和 operator<<()(左)必须在 operator<<()(右)之前调用

更多信息请看这里:
What are all the common undefined behaviours that a C++ programmer should know about?

What are all the common undefined behaviours that a C++ programmer should know about?

关于C++移位运算符优先级怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/996844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com