我知道在C++中为基类声明虚拟析构函数是一个好习惯,但是virtual即使对于作为接口的抽象类来说,声明析构函数总是很重要吗?请提供一些理由和示例原因.
我有一个基类和派生类的层次结构。基类具有一个虚函数,该虚函数被派生类覆盖。
class Base
{
public:
~Base();
virtual void other_functionality() = 0;
};
class Derived : public Base
{
public:
~Derived ();
void other_functionality() {//some code};
};
Run Code Online (Sandbox Code Playgroud)
现在,如果我这样做:
int main()
{
Base * P = new Derived ();
delete p;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它给出错误:
删除具有非虚拟析构函数的多态类类型的对象。
但是使用unique_ptr,它会通过而不会发出警告。
int main()
{
std::unique_ptr<Base> p;
p.reset(new Derived ());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道我是否使用虚拟析构函数。用裸露的指针警告将得到解决。但是问题仍然存在-为什么没有虚拟析构函数会显示裸指针而不是unique_ptr问题。