3

从设计的角度来看,请忽略可疑的继承模式。谢谢 :)

考虑以下情况:

#include <memory>

struct Foo;

struct Bar : std::unique_ptr<Foo> {
    ~Bar();
};

int main() {
    Bar b;
}

在 GCC 和 Clang 中,将其编译为独立的 TU 会引发错误:

In instantiation of 'void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = Foo]':
  required from 'std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = Foo; _Dp = std::default_delete<Foo>]'
error: invalid application of 'sizeof' to incomplete type 'Foo'
  static_assert(sizeof(_Tp)>0,
                      ^

这是 GCC 的,Clang 的类似,并且都指向struct Bar. 此外,在修复错误 添加缺少的定义:main()

// Same as above

struct Foo { };

Bar::~Bar() = default;

在我看来,std::unique_ptr在定义时需要正确实例化 ' 的析构函数并不正确Bar,因为它仅由Bar' 外线定义的析构函数调用。

我发现更奇怪的是,在其他所有内容之后添加定义,在它们不应该到达的地方,显然可以解决问题。

第一个片段应该是正确的,如果不是,为什么?修复它的第二个发生了什么?

4

0 回答 0