Pau*_*zak 4 c++ optimization gcc clang
该程序使用-std=c++20标志构建:
#include <iostream>
using namespace std;
int main() {
auto [n, m] = minmax(3, 4);
cout << n << " " << m << endl;
}
Run Code Online (Sandbox Code Playgroud)
当不使用3 4优化标志时产生预期结果。-Ox带有优化标志,它输出0 0. 我用多个带有-O1,-O2和-O3标志的 gcc 版本进行了尝试。
Clang 13 工作正常,但 clang 10 和 11 输出0 4198864具有优化级别-O2及更高级别。icc 工作正常。这里发生了什么?
代码在这里: https: //godbolt.org/z/Wd4ex8bej
采用两个参数的重载std::minmax返回一对对参数的引用。然而,参数的生命周期在完整表达式结束时结束,因为它们是临时的。
因此,输出行正在读取悬空引用,导致程序出现未定义的行为。
相反,您可以使用std::tie按值接收:
#include <iostream>
#include <tuple>
#include <algorithm>
int main() {
int n, m;
std::tie(n,m) = std::minmax(3, 4);
std::cout << n << " " << m << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用std::initializer_list的重载std::minmax,它返回一对值:
#include <iostream>
#include <algorithm>
int main() {
auto [n, m] = std::minmax({3, 4});
std::cout << n << " " << m << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |