The function f1
creates an instance of foo
and sets foo.ptr[0] = 2
.
#include <iostream>
using namespace std;
class foo {
public:
int *ptr;
inline foo(int a) {
ptr = new int[a];
}
inline ~foo() {
delete[] ptr;
}
};
foo f1() {
foo a(5);
a.ptr[0] = 2;
return a;
}
int main() {
foo a = f1();
cout<<a.ptr[0]<<endl;
return 0;
}
What I expected as the output: junk value.
f1
returns by value, which means a copy of a
is made and this copy even shares the same memory locations at which their (a
and it's copy) respective ptr
s point at.
Outside f1
, a
gets destroyed.
It's destructor is called which will deallocate ptr
's memory. This means the memory location which the copy's ptr
points at is also invalid. So, I expect a junk value as output.
The output actually is 2
.
Why?