删除派生类后,基本内存仍可访问

问题描述 投票:0回答:1

基类中没有显式的析构函数。然后,我用派生指针删除派生类。之后,如果我访问派生类的成员,则发生崩溃。但是,如果我访问基本成员,程序仍然可以。为什么?

class Base {
public:
    virtual void doSomething() = 0;
protected:
    virtual ~Base() {} // if I remove the destructor, then the program still run ok even if I remove the derived class.
};

class Derived: public Base {
public:
    Derived() {}
    ~Derived() {}
    void doSomething() override { a_ = true; }
private:
    bool a_;
};

Derived *pD = new Derived();
Base *pB = static_cast<Base*>(pD);
delete pD;

pB->doSomething(); // the program is ok if I remove the destructor in base class
pD->doSomething(); // the program crash no matter the destructor of base class is there or not.

c++ destructor derived-class
1个回答
1
投票

如果我访问派生类的成员,崩溃就发生了。

如果我访问基本成员,该程序仍然可以。为什么?

因为通过无效指针访问的行为是未定义的。

© www.soinside.com 2019 - 2024. All rights reserved.