Dia*_*ger 5 c++ linux solaris stream
我有一个非常简单的测试程序,它使用istringstreams从std :: string读取整数.代码是:
std::map<int, int> imap;
int idx, value;
std::string str("1 2 3 4 5 6 7 8");
istringstream is(str);
while(is >> idx >> imap[idx]){
cout << idx << " " << imap[idx] << endl;
}
cout << endl;
std::map<int, int>::iterator itr;
for(itr = imap.begin(); itr != imap.end(); itr++){
cout << itr->first << " " << itr->second << endl;
}
Run Code Online (Sandbox Code Playgroud)
当我在Solaris 10上运行它时,它会产生以下输出:
1 2
3 4
5 6
7 8
1 2
3 4
5 6
7 8
Run Code Online (Sandbox Code Playgroud)
但是,当我在CentOS 7下运行时,我得到:
1 0
3 0
5 0
7 0
1 4
3 6
5 8
7 0
4204240 2
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么它在Linux下会比在Solaris下有所不同?在读入地图索引之前,显然已将值读入地图,但我不知道为什么.我可以通过稍微更改代码使其在Linux下运行:
std::map<int, int> imap;
int idx, value;
std::string str("1 2 3 4 5 6 7 8");
istringstream is(str);
while(is >> idx >> value){
imap[idx] = value;
cout << idx << " " << imap[idx] << endl;
}
std::map<int, int>::iterator itr;
for(itr = imap.begin(); itr != imap.end(); itr++){
cout << itr->first << " " << itr->second << endl;
}
Run Code Online (Sandbox Code Playgroud)
我知道这是一个有效的解决方案,但我周围的人都想知道它为何与众不同.我们正在从Solaris迁移到Linux,当这样的事情发生时,他们想知道原因.我不知道为什么我要求指导.
is >> idx >> imap[idx]
Run Code Online (Sandbox Code Playgroud)
这个表达式相当于
operator>>(operator>>(is, idx), imap.operator[](idx))
Run Code Online (Sandbox Code Playgroud)
对同一函数的参数的评估相对于彼此没有排序; 任一operator>>(is, idx)或imap.operator[](idx)可以首先评估(即,无论是is >> idx或imap[idx]可以首先被评估).如果首先评估后者,那么结果是一个左值,它引用与地图中旧值相对应的值idx; 这个值将被第二次读取覆盖,而不是与新值相对应的值idx.
修改后的代码通过确保idx在imap[idx]访问之前读取来修复此问题.
| 归档时间: |
|
| 查看次数: |
119 次 |
| 最近记录: |