Search code examples
c++destructordynamic-memory-allocation

Deleting dynamically allocated objects with private destructors


So I came across a code snippet which demonstrated that if we want forced dynamic allocation of any class object, we should make its destructor private.

I tried that and yes it doesn't allow one to instantiate object on stack. But when I instantiated a dynamically allocated instance and tried deleting the object (or it would cause leak) - I kept on getting warning about destructor being private.

How can I properly manage memory of a dynamically allocated object which has a private destructor?


Solution

  • Like accessing any other private member function, you must do it in a member or a friend function. An example:

    class foo {
        ~foo(){}
    public:
        static void del(const foo* ptr)
        {
            delete ptr;
        }
    };
    

    Or even better, force the client to use smart pointer:

    class foo {
        ~foo(){}
        struct deleter {
            void operator()(const foo* ptr)
            {
                delete ptr;
            }
        };
    public:
        static std::unique_ptr<foo, deleter> make(/*args*/)
        {
            return {new foo(/*args*/), {}};
        }
    };