Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++, object created on the heap vs. local - when returning a pointer

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?

like image 938
Niklas Avatar asked Feb 17 '26 15:02

Niklas


1 Answers

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.

like image 61
hmjd Avatar answered Feb 20 '26 05:02

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!