Boost logo

Boost Users :

From: Tom Widmer (tom_usenet_at_[hidden])
Date: 2006-01-17 10:11:57


Pierre THIERRY wrote:

>>Once a pointer ends up in a shared_ptr, there's no way to get it out
>>of one, so independently creating 2 shared_ptrs that both own the same
>>memory location is a recipe for disaster.
>
>
> Who said it had to be independent? As I see it, the implementation could
> be:
>
> shared_ptr & operator=(T * r)
> {
> reset(r);
> return *this;
    }

Yes, but:

shared_ptr<Foo> fooptr;
Foo* ptr = new Foo;
fooptr = ptr;
fooptr = ptr; //boom

There are thousands of possible bugs like the above that can be caused
by an "automatic" shift to shared_ptr - remember, a shared_ptr must be
the *unique* owner of a raw pointer.

>>There's always "shared_ptr<Foo> ptr_foo( new Foo );", which is less
>>typing than either anyways.
>
>
> But only possible at the construction. In any other place, you have to
> use reset. And the problem is, I have to modify deeply my code to use
> shared_ptr, and change it back if I stop using them.

You can avoid that:

typedef shared_ptr<Foo> fooptr;
fooptr p;
//...
f = fooptr(new Foo);

That doesn't need to change if you change back to:
typedef Foo* fooptr;
However, that change is unlikely to work (since you'll suddenly have
memory leaks at best), but you could at least quite easily change to:
typedef mysmartptr<Foo> fooptr;

> With the operator=(T*), it would need no more than a modified typedef
> for the entire code to switch to or from shared_ptr (or from any other
> type of pointer that supports this operator).

Changing the typedef like that is likely to introduce a huge number of
bugs to your code! Remember, when a shared_ptr is given a raw pointer,
it takes ownership of that pointer. If anything else still owns that
pointer (or multiple shared_ptrs are separately given ownership of the
raw pointer), your code is going to perform double deletions. Requiring
explicit transfer at least forces you to examine every ownership
transfer in the code to make sure it is valid, and to change it if not.

Tom


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