c++ - 类型不完整的 std::unique_ptr 将无法编译

标签 c++ unique-ptr incomplete-type libc++

我正在使用带有 std::unique_ptr 的 pimpl-idiom :

class window {
  window(const rectangle& rect);

private:
  class window_impl; // defined elsewhere
  std::unique_ptr<window_impl> impl_; // won't compile
};

但是,我在 <memory> 的第 304 行收到关于使用不完整类型的编译错误。 :

Invalid application of 'sizeof' to an incomplete type 'uixx::window::window_impl'

据我所知,std::unique_ptr应该能够与不完整的类型一起使用。这是 libc++ 中的错误还是我在这里做错了什么?

最佳答案

以下是一些类型不完整的 std::unique_ptr 示例。问题在于破坏。

如果你使用 pimpl 和 unique_ptr,你需要声明一个析构函数:

class foo
{ 
    class impl;
    std::unique_ptr<impl> impl_;

public:
    foo(); // You may need a def. constructor to be defined elsewhere

    ~foo(); // Implement (with {}, or with = default;) where impl is complete
};

因为否则编译器会生成一个默认的,它需要一个完整的 foo::impl 声明。

如果你有模板构造函数,那么你就完蛋了,即使你不构造 impl_ 成员:

template <typename T>
foo::foo(T bar) 
{
    // Here the compiler needs to know how to
    // destroy impl_ in case an exception is
    // thrown !
}

在命名空间范围内,使用 unique_ptr 也不起作用:

class impl;
std::unique_ptr<impl> impl_;

因为编译器必须知道如何销毁这个静态持续时间对象。解决方法是:

class impl;
struct ptr_impl : std::unique_ptr<impl>
{
    ~ptr_impl(); // Implement (empty body) elsewhere
} impl_;

关于c++ - 类型不完整的 std::unique_ptr 将无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9954518/

相关文章:

c++ - MtGox API 和 websocketpp

c++ - 为什么我们不能将 "="用于 shared_ptr 或 unique_ptr?

c++ - 如何使用 unique_ptr 执行 dynamic_cast?

c++ - 替代初始化唯一指针的 vector

c++ - 指向不完整类型的指针

c - 为什么我一直得到 "error: variable has incomplete type ' struct intVec'?

c++ - 不完整类型的 std::unique_ptr 无法编译

c++ - 获取对象的类型

c++ - 如何正确关闭用 fdopen 打开的套接字?

c++ - 32位和64位系统之间的通信