Reputation: 13437
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:
Why is the reference still valid?
Upvotes: 2
Views: 152
Reputation: 1146
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
Upvotes: 2
Reputation: 254751
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.
Upvotes: 3
Reputation: 21123
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.
Upvotes: 5