【发布时间】:2015-09-08 19:58:58
【问题描述】:
我正在为游戏开发模板化组件系统。它将项目保存在一个向量中,并有两个部分特化:一个用于 POD 类型,另一个使用 std::unique_ptr。 std::unique_ptr 向量的模板化特化无法编译,但在非模板化代码中使用 std::unique_ptr 向量可以正常工作。我一直在寻找解决这个问题的方法,但不幸的是,我对 C++11/C++14 的了解还不够完善;我做错了什么?
最小示例(剥离到问题区域):
#include <vector>
#include <memory>
template<typename T>
class component
{
public:
class handle
{
friend class component;
protected:
std::size_t inner;
};
component<T>::handle add(const T& t)
{
items.push_back(t);
handle h;
h.inner = items.size() - 1;
return h;
}
protected:
std::vector<T> items;
};
template<typename T>
class component<std::unique_ptr<T>>
{
public:
class handle
{
friend class component;
protected:
std::size_t inner;
};
component<std::unique_ptr<T>>::handle add(const std::unique_ptr<T>& t)
{
items.push_back(std::move(t));
handle h;
h.inner = items.size() - 1;
return h;
}
protected:
std::vector<std::unique_ptr<T>> items;
};
这是测试代码
int main()
{
// This works fine.
component<int> pod_component;
pod_component.add(5);
// This works, too!
std::vector<std::unique_ptr<int>> pointer_vector;
pointer_vector.push_back(std::make_unique<int>(5));
component<std::unique_ptr<int>> pointer_component;
// Why doesn't this compile?
pointer_component.add(std::make_unique<int>(5));
return 0;
}
这是 gcc (4.9.3 Gentoo) 的错误输出:
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
我希望比我更擅长 C++ 的人可以帮助我和未来的读者理解这个棘手的问题。
【问题讨论】:
-
items.push_back(std::move(t));回退到复制,因为t是const引用
标签: c++ templates c++14 unique-ptr