优化行为的差异

时间:2015-10-01 01:23:24

标签: c++ reference

我得到以下程序的不同结果,具体取决于我是否启用了优化。

我希望看到10张打印出来,但是当我启用了优化后,我会打印随机值。

GCC和Clang都会发生这种情况。看起来构造函数正在优化,因为如果我在构造函数中添加一个输出语句,即使使用优化也能得到预期的结果。有人可以解释我错过了什么吗?是不确定的行为?

#include <iostream>

using namespace std;

struct wrapper
{
    const int &ref;
    wrapper(const char &t):ref(t)
    {//cout<<"";  If I un-comment this statement, I get the expected result
    }
};


int main() {
    int a=10;
    char c=a;
    cout<<wrapper(c).ref<<endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

这应该是未定义的行为,因为gcc说:

prog.cc: In constructor 'wrapper::wrapper(const char&)':
prog.cc:8:33: warning: a temporary bound to 'wrapper::ref' only persists until the constructor exits [-Wextra]
     wrapper(const char &t):ref(t)
                                 ^