Search code examples
c++virtualdestructorunique-ptrprotected

how to use std::unique_ptr<Parent> with readonly Parent class that have protected virtual destructor


test.cpp, minimum test code

#include <memory>
class Parent{ // A Interface That I can't modify! can't add 'friend' or modify 'protected'
protected:
    virtual ~Parent(){};
public:
    // other interfaces that no one is suitable for 'delete this'
};

class Derived : public Parent{ // My class
public:
    virtual ~Derived(){}
};

class Deleter : public Parent // My deleter to use unique_ptr
{
public:
    void operator()(Parent* ptr)
    {
        delete ptr; // Actually Wrong, cannot access ptr's protected & private member
    }
};

int main(int argc, char* argv[])
{
    Deleter deleter;
    // use of std::unique_ptr<Parent> error because of delete, so define my deleter to handle delete event.
    std::unique_ptr<Parent, Deleter>(dynamic_cast<Parent*>(new Derived()), deleter);
    return 0;
}

As code above.

There is a read only interface class 'Parent' with protected virtual destructor.

unique_ptr<Parent> or shared_ptr<Parent> will be use to manager objects of classes derived from Parent.

But direct use of unique_ptr<Parent>( new Derived()) result with compile error because of delete operate.

With the limit of not to edit definition of Parent class. I try to make a deleter which has the ability to delete pointers point to Parent.

After some test, I found in method of Derived class, Parent object's protected & private member cannot be access.

I'm curious about is there some solutions, to use unique_ptr<Parent> without modify definition of Parent class.

Thanks for helping me.


Solution

  • You could do:

    class DerivedDeleter
    {
    public:
        void operator()(Parent* ptr) const
        {
            delete dynamic_cast<Derived*>(ptr);
        }
    };
    

    but issue is in case of reseting unique_ptr to Parent which is not a Derived.