2

I have the following code and I'm wondering why does it write out "22" instead of garbage

class example
{

public:

    example(int ea) : ref(ea)
    {
    }

    int& ref;
};

int main ()
{
    example obj(22);

    cout << obj.ref; // Writes out 22

    return 0;
}

I think this should happen:

  • obj(22) gets an implicit conversion of 22 to a temporary integer
  • the integer is copied to the int ea parameter
  • ref is initialized with a reference to the ea parameter
  • the ea parameter is destroyed

Why is the reference still valid?

2
  • 1
    @SongWang: The reference member of the example object refers to the constructor argument, whose lifetime ends with the constructor. Commented Apr 2, 2013 at 17:36
  • 1
    "why does it write out "22" instead of garbage" It's doing both. The compiler is not going to take any measures to make sure your garbage isn't still 22. Commented Apr 2, 2013 at 17:36

3 Answers 3

5

Short answer: It's not valid, it just happens to work.

Long answer: Your order of events is correct. The reference points to a variable that has gone out of scope (at the end of the constructor). As such, it is a dangling reference. Any use of that reference from that point forward exhibits undefined behavior. In this case, it happens to print out the value, but it could just as easily do anything else.

Sign up to request clarification or add additional context in comments.

Comments

3

The reference is not still valid, and accessing the memory it refers to gives undefined behaviour. For you, it happens to refer to some memory that once contained an integer with the value 22, and hasn't yet been reused.

Comments

2

Its undefined behavior.

Try this code to see the difference:

example obj(22);
example obj2(33);
example obj3(44);

cout << obj.ref; // <-- writes out 44 instead of 22

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.