【发布时间】:2016-03-21 05:17:57
【问题描述】:
我有以下模板类(精简为仅包含相关部分),其中包含一个用 C++ 11 编写的名为 Push 的方法:
template<class T, int Capacity>
class CircularStack
{
private:
std::array<std::unique_ptr<T>, Capacity> _stack;
public:
void Push(std::unique_ptr<T>&& value)
{
//some code omitted that updates an _index member variable
_stack[_index] = std::move(value);
}
}
我的问题是:
我应该在
Push中使用std::move还是std::forward?
我不确定std::unique_ptr<T>&& 是否有资格作为通用参考,因此应该使用forward 而不是move。
我对 C++ 相当陌生。
【问题讨论】:
-
如果您来自管理语言,请尽量不要模仿“引用-”方法。在 C++ 中,对象数组在大多数情况下应该是对象数组,而不是使用
new动态填充的引用数组。请记住这一点。 -
感谢您的提示,如果
Push将获得继承T的类型实例,std::unique_ptr<T>是否可以? -
@keith 是的,
std::unique_ptr对于拥有多态类型的容器是合理的,就像你描述的情况一样。