I get different results for the following program, depending on whether I have optimizations enabled or not.
I was expecting to see 10 printed out, but when I have optimizations enabled, I get random values printed.
This happens on both GCC and Clang. It looks like the constructor is getting optimized out, because if I add an output statement in the constructor, I get the expected results even with optimization. Could somebody please explain what I am missing? Is it undefined behavior?
#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;
}