From: Ben S. <bs...@vr...> - 2001-10-07 00:30:51
|
i've been taking a look at a way to share a pointer to an object without having to decide who has to delete it. basically, i want to have both object A and object B maintain a pointer to object C and not have to decide which of A and B needs to delete object C. as far as i've seen, there are a couple of ways to do this and they generally involve maintaining a count somewhere of the number of references to the managed object and deleting that object when the count reaches zero (nobody is using the object anymore). usually a "smart" pointer is written that overloads the -> and * operators so that it acts like a pointer. include: 1. embedded attached - the reference count is a member of the object you're pointing to. the smart pointer increments the count when the object is referenced and decrements the count when the smart pointer is done using the object. i've implemented this before and have example code if you want to look at it. 2. placement attached - mangle the new and delete operators by overloading them ... somehow the reference count is maintained here. i'm a little fuzzy on how this one works. 3. indirect detached - the smart pointer contains a pointer to a helper object which maintains the reference count and the pointer the the object. 4. direct detached - the smart pointer contains a pointer to the object and a pointer to the reference count which is shared amongst all smart pointers pointing to that same object. boost (www.boost.org) provides a shared_ptr class which implements the direct detached method. (thanks for pointing it out to me kevin!) i finally figured out how it worked and wanted to share it with you all. basically it allows me to write code like: ---------------------------------- class Obj { public: Obj( int _x ) : x(_x) {} ~Obj() { std::cout<<"Destroying Foo with x="<<x<<"\n"; } private: int x; }; typedef boost:shared_ptr<Obj> ObjPtr; int main() { std::vector<ObjPtr> objList; ObjPtr p1 = new Obj( 2 ); objList.push_back( p1 ); ObjPtr p2 = new Obj( 3 ); objList.push_back( p2 ); return 0; } ------------------------- note that i never explicitly delete an instance of Obj. instead, when the objList vector gets destroyed upon exit from main(..) each shared_ptr is destroyed which decrements the count on the Obj instance it points to. when the count gets to zero, they're deleted for me automagically! ----- Ben Scott President ISU Game Developers Club Treasurer ISU Ballroom Dance Company bs...@ia... |