我将 pimpl-idiom 与 std::unique_ptr
一起使用:
class window {
window(const rectangle& rect);
private:
class window_impl; // defined elsewhere
std::unique_ptr<window_impl> impl_; // won't compile
};
但是,在
<memory>
的第 304 行,我收到有关使用不完整类型的编译错误:据我所知,
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/43229354/