Boost logo

Boost Users :

From: Richard Damon (Richard_at_[hidden])
Date: 2008-04-24 19:20:25


Lex,
Both

shared_ptr<Foo> bla(new Foo(fooInstance));

And

Shared_ptr<Foo> bla;
bla = shared_ptr<Foo>(new Foo(fooInstance));

will end up with bla pointing to the new Foo. The second will create a
temporary which will go away.

Note that neither of these will end up with bla pointing to fooInstance, but
only a copy of fooInstance created with the copy constructor onto the heap.

If you really want bla to point to fooInstance then you need to use

bla.reset(&fooInstance)

BUT there are several condition that need to be satisfied or you have just
set a time bomb in your program.

1st, fooInstance needs to be on the heap, and created by new. Your example
code has fooInstance being a non-heap object, either on the stack if the
declaration was in a function, or a global. This will lead to undefined
behavior as soon as bla no longer points to fooInstance, or when bla goes
out of scope, as the shared_ptr will try to delete something which was not
new'ed

2nd, is fooInstance is on the heap, you need to be sure that no one else is
going to delete fooInstance or you end up with a double delete. This is why
the idiom is to stuff the pointer into the shared_ptr immediately, as that
reduces the chances of letting the pointer get "owned" by multiple things.

Richard Damon

-----Original Message-----
From: boost-users-bounces_at_[hidden]
[mailto:boost-users-bounces_at_[hidden]] On Behalf Of Lex Fridman
Sent: Thursday, April 24, 2008 5:35 PM
To: boost-users_at_[hidden]
Subject: [Boost-users] shared_ptr Initial Assignment

Hi,

Say I have a class definition:
class Foo() {...};

And an instance of that class:
Foo fooInstance;

I would like to create a shared_ptr pointing to this instance of Foo.
Most documentation recommends the following way to do it:
shared_ptr<Foo> bla(new Foo(fooInstance));

But can I also do this:
shared_ptr<Foo> bla;
bla = shared_ptr<Foo>(new Foo(fooInstance));

Are there any problems with the second (or the first) method?

Thanks,
Lex


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net