when I create an object inside a function it should be automatically deleted when the function exists. e.g. the object F should be automatically deleted when getFoo() exits. However still we are able to access F when we call getFoo. How?
Foo getFoo()
{ Foo F;
return F;
}
You are not accessing the object which was created inside the function. A copy is made on the stack before returning from the function. And of course the object which was created inside the function scope was destroyed when the function returned. By destruction, I mean the location on the stack on which it existed is no more valid.
The object is copied to the caller.
Theoretically the following code
Foo a = getFoo();
even funnier is this
Foo b;
b = getFoo();
Thankfully modern compiler support return value optimization to prevent this. This also is also one of the very few exceptions to the "as if" mantra regarding code-optimizations.
You may test this with your favorite debuger with this example code (tip: note the addresses of the objects):
struct A {
A() {
i = 0;
}
A(const A& o) {
i = o.i;
}
A& operator=(A& o) {
i = o.i;
return *this;
}
~A() {
i = 0;
}
int i;
};
A getA() {
A a;
return a;
}
int main(){
A a = getA();
A b;
b = getA();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With