The code below will print 10
, but the t1
object (created in the function assign
) no longer exists by the time the print happens, so is the ptr
pointer pointing to unallocated memory space that still holds the value 10?
#include <iostream>
class Test1 {
public:
int a;
};
class Test2 {
public:
Test1* ptr;
};
void assign(Test2& t2) {
Test1 t1{10};
t2.ptr = &t1;
}
int main() {
Test2 t2;
assign(t2);
std::cout << t2.ptr->a << std::endl;
return 0;
}