...
vector<Command> cmd;
...
int build(int x) {
cmd.eb(cmd[x]);
return cmd.size() - 1;
}
...
cmd[a].c = build(cmd[a].c);
...观察以上代码。这份代码在 windows 环境下不会 runtime error,但在 linux 环境下会。
我猜测原因是 vector 扩容导致指针失效。就结果来看确实是这样。
但是为什么在 windows 环境下没问题?
我试了以下代码。
#include<bits/stdc++.h>
struct node{
int a[100];
int& operator [](int x){
std::cerr<<x<<std::endl;
return a[x];
}
}bruh;
int build(){
return bruh[1];
}
int main(){
bruh[2]=build();
return 0;
}这个玩意在 windows 下输出 1 2 ,但是在 linux 上输出 2 1。
这意味着在 windows 的编译器下,程序选择了先执行 build(),然后找到 bruh[2],把 build() 的返回值扔进去。也就是说,在第一份代码当中,vector 先执行了扩容,然后才访问了 cmd[a] 的地址,所以不会出问题。在 linux 的编译器下,则应当是先取了 bruh[2] 的地址,然后调用 build(),再把返回值扔到地址里去。
但是有一些让我不是很理解的事情。
#include<bits/stdc++.h>
struct node{
int a[100];
int& operator [](int x){
std::cerr<<x<<std::endl;
return a[x];
}
}bruh;
int main(){
bruh[2]=bruh[1];
return 0;
}这份代码在 windows 和 linux 下都输出 1 2 。这说明 linux 也不是严格的从左向右执行。
我进一步猜测,对于 linux 环境,其从右向左执行语句,使用的是类似于队列的结构,而 windows 也是从右向左执行语句,但是使用的是类似于栈的结构。即 linux 先考虑等式两侧需要的东西,再分别向下递归调用,而 windows 会就一侧使劲递归得到返回值,然后再做另一侧。
为了进一步验证,我测试了如下代码。
#include<bits/stdc++.h>
struct node{
int a[100];
int& operator [](int x){
std::cerr<<x<<std::endl;
return a[x];
}
}bruh;
int& build(int x){
return bruh[x];
}
int main(){
build(2)=build(1);
return 0;
}这份代码在 windows 和 linux 下都输出 1 2 。符合我的预期。
彩蛋:
你猜猜这份 ub 代码的来源是什么?
答案是「THUPC 2024 初赛」机器人!
非常好 ub,使我的大模拟旋转。
给我 dwt 大跌磕头了啊啊啊啊。