std::unique_ptr<T> 不完整类型错误
std::unique_ptr<T> incomplete type error
我有
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
. 这不是你想要的,但如果它有效,并且速度差异不是很大,那么它可能没问题。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误c++visual studio c2227左侧'->;Init';必须指向类/结构/联合/泛型类型