Boost logo

Boost :

From: Stewart, Robert (stewart_at_[hidden])
Date: 2002-03-21 14:41:16


From: E. Gladyshev [mailto:egladysh_at_[hidden]]
>
[the following is in reference to a function foo() -- renamed fool() -- that
takes a pointer and assumes ownership of it by using shared_ptr]

> 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>
void
fool(T const & value_i)
{
    ...
}

template <typename T>
void
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.

Rob
Susquehanna International Group, LLP
http://www.sig.com


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk