0

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;
}

1 Answer 1

1

It should be undefined behavior since gcc says:

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)
                                 ^
3
  • Note: OP would have expected output by changing const int &ref into const char &ref.
    – Jarod42
    Commented Oct 1, 2015 at 12:28
  • The expected output is 10 (ASCII for newline). By using char reference, the newline gets printed. The whole idea was to try and get the integer value for the char printed (I do know about casts!). I settled for having an actual int member in the wrapper.
    – SPMP
    Commented Oct 1, 2015 at 15:40
  • @user2308211: Replacing const int& ref; by int value; would also solve your issue.
    – Jarod42
    Commented Oct 1, 2015 at 23:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.