假设我具有菱形层次结构,如下面的代码所示。

class A {

public:
    A() {}
    int a = 3;
    virtual void aa() {}
};

class B : public virtual A {
public:
    B() : A() {}

    int b() { return 4; };
};

class C : public virtual A {
public:
    C() : A() {}
};

class D : public B, public C {
protected:
    int d = 45;

public:
    D() : B(), C() {}
};

我有这样的主要:
int main() {
    std::unique_ptr<A> a = std::make_unique<D>();
}

以上主要导致分割错误。但是,将a.release()添加到main中可解决分段错误。这是为什么?

最佳答案

这是因为A中没有虚拟Dtor。如果没有Dtor,则可以看到在使用GDB运行时对象破坏中正在发生段错误:

eddy@eddy-VirtualBox:~/deleteme$ g++ -std=c++14 -O0 -g test.cpp
eddy@eddy-VirtualBox:~/deleteme$ gdb a.out
(gdb) run
Starting program: /home/eddy/deleteme/a.out

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff76f2c01 in __GI___libc_free (mem=0x555555769e88) at malloc.c:3123
3123    malloc.c: No such file or directory.
(gdb) bt
#0  0x00007ffff76f2c01 in __GI___libc_free (mem=0x555555769e88) at malloc.c:3123
#1  0x0000555555554f6d in std::default_delete<A>::operator() (this=0x7fffffffddd8, __ptr=0x555555769e88) at /usr/include/c++/7/bits/unique_ptr.h:78
#2  0x0000555555554e07 in std::unique_ptr<A, std::default_delete<A> >::~unique_ptr (this=0x7fffffffddd8, __in_chrg=<optimized out>)
    at /usr/include/c++/7/bits/unique_ptr.h:268
#3  0x0000555555554b68 in main () at test.cpp:33

向类A添加虚拟析构函数可以解决此问题:
public:
    A() {}
    int a = 3;
    virtual void aa() {}
    virtual ~A() = default;
};

10-05 19:04