I'm still new to c++ and have been studying object scope.
I've tested the code below and witnessed some weird behaviors.
struct Test
{
int value, value2;
Test() : value(1), value2(10) {};
};
Test* GetTestPointer() {
Test t;
t.value = 20;
return &t;
}
int main() {
Test* tp = GetTestPointer();
int a = tp->value;
int b = tp->value2;
cout << a << endl;
cout << b << endl;
return 0;
}
Output:
20
10
I thought Test t
would go out of scope so dereferencing its values in main would either throw an exception or an empty value. Why is it getting valid values as if the object is still alive?
Actually this is what I originally tried:
Test* tp = GetTestPointer();
cout << tp->value << endl;
cout << tp->value2 << endl;
Output:
20
18223279
Here value2
is acting like it's invalid but I can get value
just fine.
Conversely I tried reordering them:
Test* tp = GetTestPointer();
cout << tp->value2 << endl;
cout << tp->value << endl;
Output:
10
1459403656
Note that none of this happened when I properly initiated tp
with new
, as expected.
I know I would never write code like this in real life but I got really curious as to why any of this is happening.
- When does
t
go out of scope in this case? - What does the ordering of
cout
have anything to do with whattp
is dereferencing? - Why when I save them in buffers can I get the correct values?