c++:以下代码崩溃

标签 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

如果我从基类中删除私有(private)成员“int x”,它工作正常

最佳答案

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

关于c++:以下代码崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2235137/

相关文章:

c++ - 可变参数模板特化,std::enable_if,SFINAE

android - dlopen 失败 : cannot locate symbol "cblas_sdsdot" referenced by "libgsl.so"

c++ - 删除后访问指针

c++ - 将 std::vector 转换为 char*

python - 删除python中继承的dict元素

c++ - 如何使 cin 只接受一位数字 C++

c++ - 编译器真的强制执行纯虚拟析构函数吗?

C++ 析构函数导致崩溃

C++循环引用问题

cuda - "warning: __host__ annotation on a defaulted function is ignored"<- 为什么?