c++:多态性+多重继承顺序。继承顺序重要吗?

c++: polymorphism + multiple inheritance order. Is the inheritace order significant?

我正在尝试解决类似于以下代码的一些谜团:

struct Interface {
    virtual void f () = 0;
}

struct SomeClass {
    virtual void additionalBehaviour () = 0;
    void g () {
        additionalBehavoiur ();
        /*Some stuff with printing into a ostringstream*/
    }
}

struct Derived : public SomeClass, public Interface {
    void additionalBehaviour () { /*Some printing to oss*/ }
    void f () { g (); }
}

int main () {
    unique_ptr<Interface> ifc (new Derived ());
    ifc->f ();
    cout << "HI!" << endl;
    return 0;
}

它有效,但随机退出导致 с0000005 0a9e appcrash on Windows 部分完成 g () 中列出的事情 打印 "HI!".
因此,在某些时候它会停止打印到文件中,完成其他所有操作,最后崩溃。一些点意味着确实 一些 点:例如,file << "phrase" 可能产生 phra,之后什么都没有。
此外,它在 GDB 中执行时正确执行并且不会崩溃。根据内存博士的说法,没有内存泄漏。

解决方法:

struct Derived : public Interface, public SomeClass {
    void f () { g (); }
}

问题:为什么?!
我想这是关于 类 中的相对字段位置的问题,但是在 GDB 中没有崩溃并且没有内存问题的迹象呢?

看来问题与你没有虚析构函数有关。这就是执行 g() 中处理的原因:崩溃发生在 unique_ptr 销毁对象时。

像这样它应该可以工作:

struct Interface {
    virtual void f () = 0;
    virtual ~Interface() {};
};

Online demo

标准参考:

5.3.5/3: In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.