c++ - 为什么我的程序在 O0 和 O2 的优化级别返回不同的结果

标签 c++ gcc compiler-optimization

这是我的代码:

#include<iostream>

const int & Min(const int& a, const int& b);


int main() {
    using namespace std;

    auto&& val = Min(1,2);

    cout << val << endl;
    return 0;
}


const int & Min(const int& a, const int& b) {
    return a < b ? a : b;
}

如果我用 O0 选项编译它,g++ -O0 main.cpp -o main,结果是 1。如果我使用 O2 选项编译,g++ -O2 main.cpp -o main,结果将是 0。

为什么这会给出不同的结果?

最佳答案

您的代码有 undefined behavior .

对于Min(1,2);,构造了两个从12初始化的临时对象,然后绑定(bind)到引用参数ab。请注意,临时对象会立即被销毁(在完整表达式之后)。 Min() 通过引用返回 ab;这意味着返回的引用总是悬挂的,对它的取消引用会导致 UB,即一切皆有可能。

编辑

文字(如12)不能直接绑定(bind)到引用,temporary是需要的,

Temporary objects are created when a prvalue is materialized so that it can be used as a glvalue, which occurs (since C++17) in the following situations:

  • binding a reference to a prvalue

关于c++ - 为什么我的程序在 O0 和 O2 的优化级别返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52808893/

相关文章:

c - 如何在 gcc 中禁用编译器优化?

c++ - 为什么将十进制转换为二进制的递归方法比迭代、使用和返回字符串的方法更快?

c++ - 为什么 sqrt() 在没有为 int 定义的 int 变量上工作正常?

vb.net - VB 2010 Express : Debug. WriteLine 在调试版本中完全优化了吗?

gcc - 对于基于 Sandy Bridge 的 Pentium,正确的特定于体系结构的选项 (-m) 是什么?

testing - 仅在 dejagnu 回归测试套件中运行 gcc 测试

java - Eclipse 的 java 编译器的参数

c++ - 导致段错误的奇怪整数值

c++ - 旋转矩阵 n 次

c++ - C++ 中指向对象的指针——堆栈/堆上有什么?