Boost logo

Boost :

From: E. Gladyshev (egladysh_at_[hidden])
Date: 2002-03-21 15:05:42

Nice solution, but it is not the point here
there are a lot of other solutions as well.

The point is that the fool() is fool and
he doesn't want to know how to make or follow
any memory mananagement/ownership contracts :).

Would not it be great if shared_ptr<>
could figure out automatically that the
pointed object has not been allocated
dynamically so it should not call
delete even wnen nobody references
the object.

In this case fool() would be able
to take the ownership temporaly with shared_ptr<>
if he likes it and the caller would not
have to worry about any ownership contrats
with this fool() and bunch of other fools.
In other words the caller should be able
to call fool() any way it likes.

int x;
fool( &x );


shared_ptr<int> x(new int]);
fool( x.get() );



[the following is in reference to a function foo() --
renamed fool() -- that
takes a pointer and assumes ownership of it by using

> The fool() function could be a generic function
> that is called from different contexts.
> fool() is very dumn and doesn't want to learn
> anything about memory allocation tricks.
> Fortunately fool() knows a very smart guy, named
> shared_ptr<>,... but is he really smart?

The problem is either that fool() takes ownership of
the pointer passed to
it and didn't document that fact or that fool()'s
caller failed to provide a
pointer that fool() could own.

To correct this problem, change fool() to one of these
two forms:

template <typename T>
fool(T const & value_i)

template <typename T>
fool(std::auto_ptr<T> & pValue_i)

In the first case, fool() clearly does not take
ownership of the value. In
the second case, fool() can take ownership of the
value if it likes. Since
pValue_i is a *non-const* std::auto_ptr<T>, fool is
free to call release()
or copy it to another auto_ptr, thus taking the
underlying pointer from the
caller. If fool() does neither of those things to
pValue_i, then the
caller's auto_ptr will delete the memory.

So, the issue is with the implicit contract between
caller and fool(). You
need to make the memory management explicit to avoid
the problem.

Susquehanna International Group, LLP

Do You Yahoo!?
Yahoo! Movies - coverage of the 74th Academy Awards®

Boost list run by bdawes at, gregod at, cpdaniel at, john at