c++ - 将 protected 析构函数虚拟化是否有用?

标签 c++ inheritance protected virtual-destructor

/*Child is inherited from Parent*/
class Parent {  
  public:  
    Parent () //Constructor
    {
        cout << "\n Parent constructor called\n" << endl;
    }
  protected:
    ~Parent() //Dtor
    {
        cout << "\n Parent destructor called\n" << endl;
    }
};

class Child : public Parent 
{
  public:
    Child () //Ctor
    {
        cout << "\nChild constructor called\n" << endl;
    }
    ~Child() //dtor
    {
        cout << "\nChild destructor called\n" << endl;
    }
};

int main ()
{
    Parent * p2 = new Child;          
    delete p2;
    return 0;
}

如果我将 Parent 的析构函数设为虚拟,则会出现错误,那么将 protected 析构函数设为虚拟的目的是什么?

最佳答案

举个例子:假设你有一个实现引用计数的基类。您有一个 addRef 和一个 release 方法,并且您希望销毁您的对象,如果(并且)内部计数器通过对 release 的调用。

因此,首先您希望您的析构函数受到保护(因为您只想从 release 中销毁对象)。

如果你打算从你的类派生,你也希望你的析构函数是虚拟的,因为当你想通过指向基类的指针销毁子对象时,你需要一个虚拟析构函数(感谢@sharptooth 的提示。 ..)

关于c++ - 将 protected 析构函数虚拟化是否有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8970466/

相关文章:

c++ - Windows 消息过程的函数指针数组

c++ - 录音/混音器软件

c++ - 按值调用 vs 按引用调用 const

c++ - boost::hold_any 构造函数是否有未定义的行为?

Java 实例化接口(interface)会导致奇怪的行为

c++ - 与派生类的虚指针混淆

Ruby 私有(private)实例变量,有异常(exception)

Java 构造函数未调用

java - 使用 Java 反射的包与 protected 保护

java - 访问扩展抽象基类的类实例的 protected 变量?