Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning local shared_ptr ok? 1

Status
Not open for further replies.

titanandrews

Programmer
Feb 27, 2003
130
US
Hi All,

A function that returns a local object is considered undefined. But why does it seem that returning a shared_ptr is ok? Even the boost examples have this:
shared_ptr<X> createX()
{
shared_ptr<X> px(new X_impl);
return px;
}

I have never run into a case where this does not work, but I just don't know why. Does anyone have an explanation?

many thanks!
 
Returning a local object is perfectly acceptable. The problem is when you return a reference to a local object, either by returning a reference or a pointer.

In this case, you are not doing either, so you are fine. The shared_ptr object is an object, not a pointer. You are returning a copy of the shared_ptr object. A copy of the local px instance is made and then it is destroyed. It is as if you did this:
Code:
int returnTwo()
{
    int i = 2;
    return i;
}
If you had a pointer to the shared_ptr object, or if you returned a reference, then you'd have problems.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top