Pure virtual destructor in C++

Can a destructor be pure virtual in C++?

标准c++允许纯虚构函数的存在, 但是前提是必须提供定义. 这个就有点矛盾. 纯虚函数还要定义? 原因因为子类的虚函数是按逆序执行的, 最后肯定会调用基类的虚构函数, 如果没有虚构函数的定义, 调用就会产生UD(undefined behavior)

如下代码:

#include <iostream>

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

/**
inline Base::~Base() { std::cout << "~Base() is executed\n"; }
*/

class Derived : public Base
{
public:
    ~Derived()
    {
        std::cout << "~Derived() is executed\n";
    }
};

int main()
{
    Base *b = new Derived();
    delete b;
    return 0;
}

gcc下编译, 链接器会报如下错误:

In function `ZN7DerivedD1Ev':
undefined reference to `Base::~Base()'

将注释部分放开后, 编译通过, 运行后的结果:

~Derived() is executed
~Base() is executed

Warning

一个类如果只包含纯虚构函数, 它就成了纯虚类(即使提供定义), 也就是我们不能创建它. 例子

#include <iostream>

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

inline Base::~Base() { std::cout << "~Base() is executed\n"; }

int main()
{
    Base *b = new Base();
    delete b;
    return 0;
}

gcc下编译, 编译报错如下:

error: invalid new-expression of abstract class type 'Base'
note:   because the following virtual functions are pure within 'Base':
note:     virtual Base::~Base()|

Another peculiar thing

我们知道, 如果子类继承自纯虚类, 那么我们必须为每个纯虚函数提供定义, 但是析构函数例外. 例子如下

#include <iostream>

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

inline Base::~Base() { std::cout << "~Base() is executed\n"; }

class Derived : public Base
{
    // no definition for destructor
};

int main()
{
    Base *b = new Derived();
    delete b;
    return 0;
}

这段代码在gcc下顺利编译运行. 结果如下:

~Base() is executed
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值