Hi Guys.
This is a design question, assuming C++ and a reference counted object hierarchy. A lot of classes in my codebase derive from a common base class (ObjectBase), which implements retain() and release() methods to increase and decrease the reference count of an object instance.
Every instance of an object may be created on the stack or on the heap, using a number of user definable memory allocators. In order for the object instance to commit suicide (delete this) in the release() method if the retainCount reaches 0, the instance must know which allocator it has been constructed with.
At the moment, I am allocating memory for an object instance using an arbitrary allocator, then call placement new to construct the object instance and call a setAllocator() method on the object to set the allocator it has been created with. If the object has been constructed on the stack, the allocator is set to NULL and release() will not call delete. This process is very redundant and potentially error prone (memory leaks, if I forget to call setAllocator, etc...) Ideally I would want to make this a one-step process like this:
Object* o = myPoolAllocator.allocate<Object>(constructor arguments... );
But this makes it very difficult to support and arbitrary number of constructor arguments.
I am just looking for ideas on how to solve this problem. I really like the idea of being able to reference count objects without having to rely on a smart pointer, especially since most classes derive from a common base, anyways.
Thanks for your help.
Florian