After working in C# or ObjC for a while you realize how painful C++ memory management can get at times. Being responsible for releasing pointers explicitly seriously hinders my program design sometimes. This is particularly a problem when doing new just can’t be avoided (unmanaged objects within managed classes), or when you’re managing a list of objects where you need a new to allow some degree of runtime polymorphism.
Then, I stumbled across this simple smart pointer class which takes care of reference counting. Its called counted_ptr and can be found here. Using this class, I allocate my objects once and let the counted_ptr class object carry it. Once I no longer need the allocated object the counted_ptr object deletes it for me. This is how I use it within my code:
void DrawLine (const dhVector<float>& start, const dhVector<float>& end, const dhColor<float>& color) {
_lastQueuedOperations.push_back (dhOperation (dhOperationType_Line,
counted_ptr<OperationParameters>(new dhLineDrawOperationParameters<float, float> (start, end, color))));
}
Here is a routine that queues a draw line operation which will be executed in a post process pass of the rendering pipeline of our 3D engine. I allocate an object of type
HTH
by nabrahamson
06 Aug 2008 at 15:51
I will have to remember this the next time I get to do some c++ hacking. Great find.
by Krishnan TR :)
06 Aug 2008 at 17:00
Hey dude – Did U consider using shared_ptr from the TR1 libraries? I think functionality wise, its very similar to what you are looking for. It maintains a reference count on all the objects the ptr is pointing to and automatically releases the resources when the reference count becomes 0. In my opinion, U will also be in tune with C++0x by using TR1 libraries which as U know, are slated to be a part of the next version of C++. What are Ur thoughts? :)
Ur code will look like (the same but) –
instead of counted_ptr<…
U will be using
std::shared_ptr pOprPmtrs(new dhLineDrawOperationParameters (start, end, color)). “pOprPmtrs” will now be pointing to the new instance of “dhLineDrawOperationParameters”.
by admin
06 Aug 2008 at 17:15
@nabrahamson
Yeah, it really makes your life easy. Since you don’t have to keep track of your pointers anymore, you can either design better or be as lazy as you want :).
@Krishnan TR
Hi Krish :), Well, I think the purpose of a shared_ptr is slightly different. It is intended more towards allowing multiple entities to hold a reference to the pointer (like counted_ptr, as you said, it indeed keeps a reference count) but only allow one of the entities to access it at one time. This is evident from the fact that you first need to acquire a lock on the pointer before you can start dereferencing it. A counted_ptr is just a raw reference counted pointer.
However, I will take a deeper look at it and see if it solves my purpose.