问题描述
我使用pimpl-idiom与 std :: unique_ptr
:
I'm using the pimpl-idiom with std::unique_ptr
:
class window {
window(const rectangle& rect);
private:
class window_impl; // defined elsewhere
std::unique_ptr<window_impl> impl_; // won't compile
};
However, I get a compile error regarding the use of an incomplete type, on line 304 in <memory>
:
据我所知, std :: unique_ptr
应该能够使用不完整的类型。这是在libc ++中的错误还是我在这里做错了?
For as far as I know, std::unique_ptr
should be able to be used with an incomplete type. Is this a bug in libc++ or am I doing something wrong here?
推荐答案
std :: unique_ptr 使用不完整的类型。
Here are some examples of std::unique_ptr
with incomplete types. The problem lies in destruction.
如果你使用pimpl和 unique_ptr
,你需要声明一个析构函数: p>
If you use pimpl with unique_ptr
, you need to declare a destructor:
class foo
{
class impl;
std::unique_ptr<impl> impl_;
public:
foo(); // You may need a def. constructor to be defined elsewhere
~foo(); // Implement (with an empty body) where impl is complete
};
因为否则编译器会生成一个默认的,它需要一个完整的声明 foo :: impl
为此。
because otherwise the compiler generates a default one, and it needs a complete declaration of foo::impl
for this.
如果你有模板构造函数,那么你被拧了,即使你不构造 impl _
成员:
If you have template constructors, then you're screwed, even if you don't construct the impl_
member:
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
不会工作:
At namespace scope, using unique_ptr
will not work either:
class impl;
std::unique_ptr<impl> impl_;
因为编译器必须知道如何销毁这个静态持续时间对象。解决方法是:
since the compiler must know here how to destroy this static duration object. A workaround is:
class impl;
struct ptr_impl : std::unique_ptr<impl>
{
~ptr_impl(); // Implement (empty body) elsewhere
} impl_;
这篇关于std :: unique_ptr具有不完整的类型将不能编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!