From: E. Gladyshev (egladysh_at_[hidden])
Date: 2002-03-22 14:10:36
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
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
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 code.
Do you think if it is a valid idea to be included in
using namespace std;
typedef map<void*, int*> object_map;
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 int
_it = p.first;
if( p.second ) *(p.first->second) = 1;
if( !--*(_it->second) )
_map.erase( _it );
//all other standard smart pointer stuff goes here
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 );
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
can reference static objects. For example:
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