c ++:下面一段代码崩溃了

Gan*_*pur 3 c++ destructor

#include <iostream>
using namespace std;

class B
{
public:
    B() { cout << "Base B()" << endl; }
    ~B() { cout << "Base ~B()" << endl; }
private:
    int x;
};

class D : public B
{
public:
    D() { cout << "Derived D()" << endl; }
    virtual ~D() { cout << "Derived ~D()" << endl; }
};

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


---- output----------
Base B()
Derived D()
Base ~B()
*** glibc detected *** ./a.out: free(): invalid pointer: 0x0930500c ***
======= Backtrace: =========
/lib/tls/i686/cmov/libc.so.6[0xb7d41604]
/lib/tls/i686/cmov/libc.so.6(cfree+0x96)[0xb7d435b6]
/usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0xb7f24231]
./a.out[0x8048948]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7ce8775]
./a.out[0x80487c1]
Aborted
Run Code Online (Sandbox Code Playgroud)

如果我从基类中删除私有成员"int x",它工作正常

Joa*_*lva 12

基类B的析构函数也必须是虚拟的.

  • @Ganesh Kundapur:你的代码有UB.请阅读FAQ 20.7 http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7,特别是最后一段. (3认同)

sha*_*oth 6

class B没有虚拟析构函数,你尝试通过指针派生delete的实例- 这是未定义的行为.您必须使析构函数虚拟化才能使代码正常工作.class Dclass Bclass Bclass B