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

时间:2018-10-15 02:14:30

标签: 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。

为什么给出不同的结果?

1 个答案:

答案 0 :(得分:14)

您的代码包含undefined behavior

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

编辑

文字(例如12)不能直接引用,而是需要temporary

  

when a prvalue is materialized so that it can be used as a glvalue, which occurs (since C++17)中创建临时对象   以下情况:

     
      
  • 将引用绑定到prvalue
  •