Let foo
be:
class Foo {
public:
Foo(int a) {
aa = a;
cout << "foo built. " << aa << endl;
}
~Foo() {
cout << "foo DIED. " << aa << endl;
}
int aa;
};
Also, assume we have:
Foo* func1(){
Foo* foo = new Foo(1);
return foo;
}
Now, running this:
{ // <---- we have braces
Foo obj = *func1();
}
yields: "foo DIED"
but running:
{
Foo &obj = *func1();
}
does not release foo's instance.
Could you please clarify what's happening here?
func1
allocates a Foo
and returns a pointer to it. Sooner or later someone must manually delete
that Foo
to free up the resources it uses. Because *func1()
dereferences the pointer before a copy of the pointer is made, the pointer is lost. Without the pointer, the object could be lost forever, preventing you from delete
ing it when you no longer need it.
Foo obj = *func1();
resulted in the creation of two Foo
s. The one dynamically allocated in func1
and another automatically allocated Foo
named obj
that is a copy of the Foo
from func1
. It is the death of obj
when it goes out of scope that you are seeing. The Foo
from func1
has been lost. You have what's called a memory leak. This code cannot be fixed. It is broken, even though it's the one that looked like it worked.
Foo &obj = *func1();
creates one Foo
, the one from func1
, and obj
merely references it. When the reference goes out of scope nothing happens. You can't refer to the object as obj
anymore, the reference is no more, but the object still exists in memory and has been leaked. But in this case while you still have obj
referencing it, you can delete &obj;
and free it.
{
Foo &obj = *func1();
delete &obj; // get address of referenced object, then delete it.
}
Now you can see the object being freed.
Long-and-short: You always have to keep a live reference or pointer to a dynamically allocated object until you manually release it.