移动unique_ptr< T>的向量 [英] Moving a vector of unique_ptr<T>
问题描述
所以我有一种情况,我需要存储一个抽象类型的向量,因为我明白这需要使用一个unique_ptrs或类似的向量。
So I have a situation where I need to store a vector of an abstract type, as I understand this requires the usage of a vector of unique_ptrs or similar.
所以为了移动包含unique_ptrs向量的类的实例,我需要定义一个我已经做的移动构造函数。
So in order to move about instances of the class which contains the vector of unique_ptrs, I need to define a move constructor which I have done.
但是,如示例所示下面,这似乎不同意编译器(msvc),它给我以下错误。
However as demonstrated by the example below, this seems to disagree with the compiler (msvc) which gives me the following error.
错误1错误C2280:'std :: unique_ptr> :: unique_ptr(const std :: unique_ptr< _Ty,std :: default_delete< _Ty >>&)':尝试引用已删除的函数
Error 1 error C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
class SomeThing{
};
class Foo{
public:
Foo(){
}
Foo(const Foo&& other) :
m_bar(std::move(other.m_bar))
{};
std::vector<std::unique_ptr<SomeThing>> m_bar;
};
int main(int argc, char* argv[])
{
Foo f;
return 0;
}
推荐答案
一个 const
的东西,因为一个移动涉及源的突变。
You can't move from a const
thing, because a move involves mutation of the source.
因此,正在尝试一个副本。
Therefore, a copy is being attempted instead. And, as you know, that's impossible here.
你的移动构造函数应该看起来像这样,没有 const
:
Your move constructor should look like this, with no const
:
Foo(Foo&& other)
: m_bar(std::move(other.m_bar))
{}
这篇关于移动unique_ptr< T>的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!