具有不完整类型的std :: unique_ptr将无法编译我正在使用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};但是,我在第304行的第304行收到有关使用不完整类型的编译错误<memory>:' sizeof'到不完整类型' uixx::window::window_impl的应用无效' '据我所知,std::unique_ptr应该可以使用不完整的类型。这是libc ++中的错误还是我在这里做错了什么?
2 回答
精慕HU
TA贡献1845条经验 获得超8个赞
以下是一些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_;- 2 回答
- 0 关注
- 989 浏览
添加回答
举报
0/150
提交
取消
