unique_ptr pimpl和不完整的类型

vso*_*tco 3 c++ pimpl-idiom c++11

这不是std :: unique_ptr的欺骗,不完整的类型将无法编译.

请考虑以下代码:

#include <memory>

struct X
{
    X();
    ~X();    

    struct Impl; 
    std::unique_ptr<Impl> up_;
};

struct Impl {}; // fully visible here

X::X() : up_{nullptr}{}
X::~X() = default;

int main()
{
    X x;
}
Run Code Online (Sandbox Code Playgroud)

Live on Coliru

gcc/clang都吐出错误说不Impl完整.但是,我提供了一个默认的析构函数,X 后面 Impl是完全可见的,所以IMO代码应该编译.为什么不呢?现在出人意料:如果我做Impl了一个内部类,即定义

struct X::Impl{};
Run Code Online (Sandbox Code Playgroud)

相反,即使没有提供析构函数,代码也会编译.为什么会这样?我们不应该提供这样的默认析构函数,至少根据第一行中提到的链接?

Mil*_*nek 11

你有两个不同的结构名称Impl.

struct X
{
    struct Impl; // Here you declare X::Impl
    std::unique_ptr<Impl> up_;  // Here you create a pointer to a X::Impl
};

struct Impl {};  // Here you declare and define ::Impl

...

int main()
{
    X x;  // Here X::Impl is still incomplete
}
Run Code Online (Sandbox Code Playgroud)