c++ - 如何将 std::unique_ptr<Parent> 与具有 protected 虚拟析构函数的只读父类一起使用

标签 c++ virtual destructor unique-ptr protected

test.cpp,最小测试代码

#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;
}

如上代码。

有一个带有 protected 虚拟析构函数的只读接口(interface)类“Parent”。

unique_ptr<Parent>shared_ptr<Parent>将用于管理从 Parent 派生的类的对象。

而是直接使用unique_ptr<Parent>( new Derived())由于删除操作导致编译错误。

限制不编辑Parent的定义类(class)。我尝试制作一个能够删除指向 Parent 的指针的删除器。

经过一些测试,我发现在Derived类的方法中,Parent对象的protected & private成员是无法访问的。

我很好奇是否有一些解决方案,可以使用 unique_ptr<Parent>不修改父类的定义。

谢谢你帮助我。

最佳答案

您的类层次结构不正确。基类的 protected 析构函数是设计以防止您尝试执行的操作。

创建除 public 之外的析构函数的原因通常是为了强制执行单例模式,或者其他一些原因来阻止破坏。多态基类几乎没有理由使用 protected 析构函数。

关于c++ - 如何将 std::unique_ptr<Parent> 与具有 protected 虚拟析构函数的只读父类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49812841/

相关文章:

c++ - 如何直接从构造函数结束 C++ 代码?

c++ - 仅为应用程序禁用页面文件?

c++ - Visual C++ 不允许 iostream

c++ - 如何从指向基类类型的指针调用派生类函数 (C++)

Delphi 类 def 导致 EStackOverflow

c++ - 通过指向基的指针删除对象,而没有虚拟析构函数

c++ - 尝试使用 while 循环将数据从文件读入数组。还必须检查以确保第一个也是唯一的值不是 -1

c++ - 返回不同类型的派生虚函数——指针

c++ - 虚拟公共(public)继承?需要帮助理解代码

c++ - 类的堆分配对象是否在其范围之后但在 C++ 中调用其析构函数之前仍然存在