Smart questions
Smart answers
Smart people
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

LINK TO THIS FORUM!

Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

Partner With Us!

"Best Of Breed" Forums Add Stickiness To Your Site
Partner Button
(Download This Button Today!)

Feedback

"...I posted a query a short while ago and had an informed answer within a couple of hours. Terrific!..."

Geography

Where in the world do Tek-Tips members come from?

Returning local shared_ptr ok?Helpful Member! 

titanandrews (Programmer)
1 Oct 09 11:37
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!
 
Helpful Member!  uolj (Programmer)
5 Oct 09 17:25
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.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close