Upcoming Events
Unite 2010
11/10 - 11/12 @ Montréal, Canada

GDC China
12/5 - 12/7 @ Shanghai, China

Asia Game Show 2010
12/24 - 12/27  

GDC 2011
2/28 - 3/4 @ San Francisco, CA

More events...
Quick Stats
88 people currently visiting GDNet.
2406 articles in the reference section.

Help us fight cancer!
Join SETI Team GDNet!
Link to us Events 4 Gamers
Intel sponsors gamedev.net search:

  Contents

 Reference Counting
 Smart Pointers
 Reference counting
 and STL

 Conclusion

 Get the Source
 Printable version

 


Reference counting and STL

A lot of times it is needed to hold objects in a data structure, and not worry about deleting them when clearing, or erasing the objects from the structure. This reference counting scheme does all of that for you. All you need to do is use structures of smart pointers, and you're done.

Example:

std::vector<RefCntPointer<MyObject> > v; v.push_back(new MyObject);

Now if you clear the vector, or erase the pointer, the object will be freed. If you want to erase it without deleting it, because you need the object somewhere, simply get the pointer and hold it before erasing:

RefCntPointer<MyObject> ptr=v[0]; v.pop_back();

Now the pointer was removed, but the object wasn't deleted. To delete it now, simply do:

ptr=NULL;



Next : Conclusion