Search code examples
c++memory-managementmemory-leakssmart-pointersreference-counting

C++ -- Smart pointer and custom memory allocation dilemma


I have a dilemma regarding Smart pointers and memory allocation.

In my smart pointer class I have my own way of allocation memory through a memory module in my engine.

template <class T>
    class Object
    {
    public:
        inline Object()
        {
            Init();

            if (mEngine)
            {
                mObj = (T*) mEngine->GetMemoryManager()->Allocate(sizeof(T));
                mRefCount = 1;
            }
        }

Now when I want to Destroy() my engine, I want all memory to freed as well. This is first of all because I want to cleanup all memory associated with my engine, and also because cleanup of mObj relies upon my memory manager as it may use for example a memory pool to allocate/deallocate memory, and removing that memory manager would lead to unallocatable memory.

So have I shot myself in the foot with smart pointers? Is there a smart way to solve this?


Solution

  • Why so? In fact, this is a common practice to have a smart pointer mixed with a custom memory management. std::shared_ptr (or boost::shared_ptr) supports a custom deleter, reference counted pointer usually have some virtual method that is called to release them etc.

    You cannot, however, destroy the engine while something else is using parts of it, like those referenced objects. For that purpose, people usually make "engine" a reference counted pointer, too. Just be careful about cyclic dependencies.

    ... and let the force be with you!