简体   繁体   中英

Do I need to define a virtual destructor even if the base and derived class only use primitive data types?

According to the C++ standard: 5.3.5/4:

If the static type of the operand [of the delete operator] is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behaviour is undefined.

Does this apply even for something such as:

class B
{
    public:
    virtual void f() const = 0;
    virtual void g() = 0;
};

class D : public B
{
    public:
    explicit D(int x) : x_ {x} {}

    void f() const override;
    void g() override;

    private:
    int x_;
};

In this case neither D nor B has anything to deallocate, so shouldn't it no longer be required to provide virtual destructors? Or is this still undefined behavior?

That statement from the standard you quote means that a sample like (using your class B and D )

int main()
{
    B *object = new D;
    delete object;
}

has undefined behaviour if B does not have a virtual destructor.

No exceptions to that rule.

It doesn't matter what the classes (or their member functions) do or don't do. It is the non-virtual destructor in B that causes the delete expression ( delete object ) to have undefined behaviour. No exceptions.

The standard doesn't make any exceptions predicated on the contents of the classes.

I would say, "Yes, you need virtual destructors."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM