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?
exampleobject refers to the constructor argument, whose lifetime ends with the constructor.