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

C++ 删除派生类后,基本内存仍可访问,c++,destructor,derived-class,C++,Destructor,Derived Class,基类中没有显式析构函数。然后,我删除带有派生指针的派生类。之后,如果我访问派生类的成员,就会发生崩溃。但是,如果我访问基本成员,程序仍然正常。为什么? 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 d

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

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.

类基{
公众:
虚空doSomething()=0;
受保护的:
virtual~Base(){}//如果我删除析构函数,那么即使我删除了派生类,程序仍然可以正常运行。
};
派生类:公共基{
公众:
派生(){}
~Derived(){}
void doSomething()重写{a_u=true;}
私人:
布尔阿瑟;
};
派生*pD=新派生();
底座*pB=静态铸造(pD);
删除pD;
pB->doSomething();//如果我删除基类中的析构函数,程序就可以了
pD->doSomething();//无论基类的析构函数是否存在,程序都会崩溃。
如果我访问派生类的成员,就会发生崩溃

如果我访问基本成员,程序仍然正常。为什么?

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++的荣耀和威严的一部分是,有大量的“未定义的行为”,语言规范基本上只是说“不要这样做——但是如果你这样做,那么不管发生什么,都会发生,你不允许抱怨,因为你不应该首先做这件事。”取消对悬空指针的引用就是这样一种未定义的行为。。。所以,不要这样做:)