std::unique_ptr<T> 不完整类型错误

std::unique_ptr<T> incomplete type error

本文关键字:gt 类型 错误 ptr lt std unique      更新时间:2023-10-16

我有

template<typename T>
class queue
{
private:
    struct node
    {
        T data;
        std::unique_ptr<node> next; //compile error on incomplete type
        node(T&& data_):
            data(std::move(data_))
        {}
    };
    std::unique_ptr<node> head;
    node* tail;
public:
        queue():
            tail(nullptr)
        {}

我在VS10的标记行上收到编译错误。在这种情况下,我不应该被允许使用不完整的类型(实例化模板 - 构造函数 - 这里以 int 为例)?有解决方法吗?

编辑

singlethreadedqueue.h(62): error C2079: 'queue<T>::node::next' uses undefined class 'std::unique_ptr<_Ty>'
1>          with
1>          [
1>              T=MyClass
1>          ]
1>          and
1>          [
1>              _Ty=queue<MyClass>::node
1>          ]
1>          c:program filesmicrosoft visual studio 10.0vcincludememory(2161) : see reference to class template instantiation 'queue<T>::node' being compiled
1>          with
1>          [
1>              T=MyClass
1>          ]
1>          c:program filesmicrosoft visual studio 10.0vcincludememory(2195) : see reference to class template instantiation 'std::_Unique_ptr_base<_Ty,_Dx,_Empty_deleter>' being compiled
1>          with
1>          [
1>              _Ty=queue<MyClass>::node,
1>              _Dx=std::default_delete<queue<MyClass>::node>,
1>              _Empty_deleter=true
1>          ]
1>         singlethreadedqueue.h(69) : see reference to class template instantiation 'std::unique_ptr<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=queue<MyClass>::node
1>          ]
1> : see reference to class template instantiation 'queue<T>' being compiled
1>          with
1>          [
1>              T=MyClass
1>          ]

模板实例化点的完整类型要求是由于std::default_delete,所以你可能可以通过提供一个自定义删除器来解决它。

struct node;         // node_delete need to know 'node' is a type.
struct node_deleter 
{                    // std::unique_ptr needs 'node_deleter' to be complete.
    void operator()(node* ptr);  // forward-reference to avoid needing
};                               //  'delete ptr' before the node is complete.
struct node
{
    std::unique_ptr<node, node_deleter> next;
};
void node_deleter::operator()(node* ptr)
{
     delete ptr;
}

请注意,我还没有在 MSVC 中测试过它,也许您应该尝试升级到 VC 11,或者提交一个错误来Microsoft即使 VC 11 也无法编译您的原始代码。

您的代码看起来格式良好。在构造函数体和析构函数体中,类被视为完整类型。

如果你使用shared_ptr而不是unique_ptr,那么这将编译(在VS2010上)。 我猜它的实现方式允许在 shared_ptr 的情况下使用部分类(前向声明等),但不适用于unique_ptr. boost::shared_ptr的文档肯定说它允许这样做,但我不知道 VS2010 是否"说"为什么他们为一个而不是另一个做这种行为。

我会说测试它,看看它是否满足你的需求shared_ptr. 这不是你想要的,但如果它有效,并且速度差异不是很大,那么它可能没问题。