Boost logo

Boost :

From: Darin Adler (darin_at_[hidden])
Date: 2002-03-24 12:08:28

On Friday, March 22, 2002, at 11:10 AM, E. Gladyshev wrote:

> In other words a function cannot claim a shared ownership of an object
> if the object is passed in with a plain pointer. This issue is
> especially important in multi-threaded applications.

The classic approach for people who care about this is to use
"intrusive" shared pointers, where the reference count is stored inside
the pointed-to object.

I'm not sure why passing around plain pointers is more important in
multi-threaded applications, but I'd prefer to take your word for it
rather than discussing it at length. Typically, the only reason you are
forced to pass around a plain pointer is some legacy code or system
programming interface you can't control, and even that is pretty rare.

> A very easy solution is to use a global object map. STL has a
> logarithmic <map> class.

Keeping a std::map of all shared pointers would enable all sorts of
features and advanced error checking. But its cost in performance is
prohibitive, even if you ignore multi-threading issues. An
implementation that works properly in multi-threaded applications would
have an even greater cost.

> The following code shows how to do that.

The "test code" you provided would not work properly in multi-threaded

> One problem that I'd like to solve is to deal with pointers to static
> objects. I am not sure if there are any smart pointer implementations
> that can reference static objects. For example:
> int g_x;
> int main()
> {
> share_ptr<int> tmp(&g_x)
> } //CRASH

The latest version of boost::shared_ptr can handle this. When you
construct a shared_ptr, you can pass in a function that is used to
destroy the object instead of the default "delete". Here's one way to do

     #include <boost/shared_ptr.hpp>
     void do_nothing(int*) { }
     int g_x;
     int main()
         boost::shared_ptr<int> tmp(&g_x, do_nothing);

Once you've had some experience with smart pointers, you'll find that
it's best to have very few interfaces that use plain pointers, so the
first problem you mentioned becomes a non-problem.

     -- Darin

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