为什么纯虚拟析构器需要实现 [英] Why a pure virtual destructor needs an implementation

查看:162
本文介绍了为什么纯虚拟析构器需要实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道需要纯虚拟析构函数的情况。我也知道,如果我们不提供它们的实现,它会给我一个链接器错误。我不明白是为什么应该是这样的代码片段如下所示:

I know the cases where pure virtual destructors are needed. I also know that If we don't provide an implementation for them it will give me a linker error. What I don't understand is why this should be the case in a code fragment as shown below:

int main()
{
    Base * p = new Derived;
}

这里没有删除,所以没有调用析构函数,所以不需要它的实现(假设它应该像其他正常的函数,声明但没有定义,链接器抱怨只有当我们调用它们)...或者我缺少一些东西?

Here there is no delete, so no call to destructor and so no need for its implementation(assuming it is supposed to behave like other normal functions which are declared but not defined, linker complains only when we call them)...or am I missing something?

我需要了解为什么这是一种特殊情况。

I need to understand why this should be a special case?

编辑

这是我的基本和派生类

class Base
{
public:
    Base(){}
    virtual ~Base() = 0;
};

class Derived : public Base
{
};


推荐答案

编译器尝试构建虚拟表, code> virtual (纯的或不是)析构函数,并且它抱怨,因为它找不到实现。

The compiler tries to build the virtual table given a virtual (pure or not) destructor, and it complains because it can't find the implementation.

virtual 析构函数不同于其他 virtual 函数,因为它们在对象被销毁时被调用,而不管它是否被实现。这需要编译器将它添加到vf表,即使它没有被显式调用,因为派生类析构函数需要它。

virtual destructors differ from other virtual functions because they are called when the object is destroyed, regardless of whether it was implemented or not. This requires the compiler to add it to the vf table, even if it's not called explicitly, because the derived class destructor needs it.

在标准的需要一个纯粹的虚拟析构函数。

Pedantically, the standard requires a pure virtual destructor to be implemented.

这篇关于为什么纯虚拟析构器需要实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆