在基类中没有显式的析构函数。然后,我使用派生指针删除派生类。之后,如果我访问派生类的成员,则会发生崩溃。但是,如果我访问基本成员,该程序仍然可以。为什么?
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.
答案 0 :(得分:1)
如果我访问派生类的成员,崩溃将会发生。
如果我访问基本成员,该程序仍然可以。为什么?
因为未定义通过无效指针进行访问的行为。