3

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
Niklas
  • 1,753
  • 4
  • 16
  • 35

5 Answers5

3

Yes, the second case is safe.

But the caller will need to delete the returned pointer. You could change this to use boost::shared_ptr and it will be destroyed when it is no longer in use:

boost::shared_ptr<person> NewPerson()
{
    boost::shared_ptr<person> pp = boost::make_shared<person>();

    return pp;
}

If C++11 then you can use std::shared_ptr or std::unique_ptr.

hmjd
  • 120,187
  • 20
  • 207
  • 252
2

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 delete the object yourself, or use some form of smart pointer.

Mat
  • 202,337
  • 40
  • 393
  • 406
1
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?

Correct on the first one: it would be returning a pointer to data on that functin's stack, which will be reclaimed and modified once the function finishes.

On the second case: the object is created on the heap, which is separate from the execution stack. When the function finishes, the object on the heap is safe and stays the same. However, C++ does not automatically do garbage collection, so if you lost all of the references to a heap object, this would constitute a memory leak--the object's space would not be reclaimed until the program ended.

Christopher Neylan
  • 8,018
  • 3
  • 38
  • 51
0

The latter is safe. However, C++ does not (usually) provide garbage-collection, and thus you need to arrange for an explicit delete of the returned object.

ibid
  • 3,891
  • 22
  • 17
0

Like you say, the first case is bad as the pointer will not be valid. As for the second case, memory in C++ is not managed, you have to clean up after yourself. C++ doesn't keep track of references on normal pointer, that's what std::shared_ptr is for.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621