Boost logo

Boost :

From: Ken Shaw (ken_at_[hidden])
Date: 2002-03-22 15:32:58


----- Original Message -----
From: "E. Gladyshev" <egladysh_at_[hidden]>
To: <boost_at_[hidden]>
Sent: Friday, March 22, 2002 1:10 PM
Subject: [boost] plain pointers and shared_ptr

>
> In my previous post, I looked at using shared_ptr<>
> with plain pointers.
> The problem is that if a caller passes an object to a
> function with a
> plain pointer, the caller has to make sure that the
> object is
> valid while the function is using this object.
> In other words a function cannot claim a shared
> owenership of an object
> if the object is passed in with a plain pointer. This
> issue
> is especially important in multi-threaded
> applications.
> The following code won't work of course.
>
> void foo( int* p )
> {
> shared_ptr<int> my_int( p ); //claim shared
> ownership
> }
>
> main()
> {
> shared_ptr<int> x( new int );
> foo( x.get() );
> } //!!CRASH shared_ptr<> will try to delete an
> object that has been deleted by foo().
>
>
> A very easy solution is to use a global object map.
> STL has a logarithmic <map> class. The following
> code shows how to do that. This is just a test code.
> Do you think if it is a valid idea to be included in
> boost?
>

An even easier solution is to simply use shared_ptr<> everywhere without
exception, it is as thread safe as any code is likely to get at present.

>
> #include <map>
> using namespace std;
>
> typedef map<void*, int*> object_map;
>
> class smart_ptr_base
> {
> protected:
> static object_map _map;
> };
>
> template <typename T>
> class smart_ptr : public smart_ptr_base
> {
> public:
>
> smart_ptr( T* d )
> {
> pair<object_map::iterator, bool> p;
> p = _map.insert( object_map::value_type( d, new int
> ) );
> _it = p.first;
> if( p.second ) *(p.first->second) = 1;
> else ++*(p.first->second);
> }
>
> virtual ~smart_ptr()
> {
> if( !--*(_it->second) )
> {
> delete (T*)(_it->first);
> _map.erase( _it );
> }
> }
>
> //all other standard smart pointer stuff goes here
> //...
>
> protected:
> object_map::iterator _it;
> };
>
> object_map smart_ptr_base::_map;
>
>
>
> void foo( A* p )
> {
> smart_ptr<A> tmp( p ); //claim shared ownership
> }
>
> int main(int argc, char* argv[])
> {
> A *p = new A();
> smart_ptr<A> tmp( p );
> foo( p );
> return 0;
> }
>
> 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
>

smart pointers are intended to simplify heap memory management. Why are you
trying to apply them to things that they cannot possibly handle?

Ken Shaw


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