This is a follow up question from
Safe in C# not in C++, simple return of pointer / reference,
Is this:
person* NewPerson(void)
{
person p;
/* ... */
return &p; //return pointer to person.
}
the same as?
person* NewPerson(void)
{
person* pp = new person;
return pp; //return pointer to person.
}
I know that the first one is a bad idea, because it will be a wild pointer.
In the second case, will the object be safe on the heap – and like in c#
go out of scope when the last reference is gone to it?
It’s safe, the object will still be alive after the return.
But don’t expect the object to be automatically cleaned up for you in C++. Standard C++ does not have garbage collection. You’ll need to
deletethe object yourself, or use some form of smart pointer.