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 dhLineDrawOperationParameters which I pass in to a counted_ptr object as a OperationParameters object, which is then passed into the dhOperation constructor and is pushed back into the list of queued operations. Once this operation is executed, I don't need to explicitly delete the allocated pointer. counted_ptr takes care of releasing the object once the reference count falls to zero.

HTH