From: E. Gladyshev (egladysh_at_[hidden])
Date: 2002-03-22 17:45:16
Just a fix for the test code... forgot to delete the
if( !--*(_it->second) )
_map.erase( _it );
--- "E. Gladyshev" <egladysh_at_[hidden]> wrote:
> In my previous post, I looked at using shared_ptr<>
> with plain pointers.
> The problem is that if a caller passes an object to
> 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.
> is especially important in multi-threaded
> The following code won't work of course.
> void foo( int* p )
> shared_ptr<int> my_int( p ); //claim shared
> 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
> Do you think if it is a valid idea to be included in
> #include <map>
> using namespace std;
> typedef map<void*, int*> object_map;
> class smart_ptr_base
> static object_map _map;
> template <typename T>
> class smart_ptr : public smart_ptr_base
> smart_ptr( T* d )
> pair<object_map::iterator, bool> p;
> p = _map.insert( object_map::value_type( d, new
> ) );
> _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
> 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
> 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
> Do You Yahoo!?
> Yahoo! Movies - coverage of the 74th Academy Awards®
> Unsubscribe & other changes:
Do You Yahoo!?
Yahoo! Movies - coverage of the 74th Academy Awards®
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk