如何声明一个unique_ptr的向量作为类数据成员? [英] How to declare a vector of unique_ptr's as class data member?
问题描述
我想有一个unique_ptr的向量作为我正在做的类的成员。
I'd like to have a vector of unique_ptr's as a member of a class I'm making.
class Foo {
[...]
private:
vector<unique_ptr<Bar>> barList;
}
但是我开始从 VS2010 编译器:
But then I start getting cryptic error messages from the VS2010 compiler:
error C2248: 'std::unique_ptr<_Ty>::operator =' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
D转到Microsoft的实现 std :: _ Copy_impl<>
...
Along with a handful of error lines below that which dive into Microsoft's implementation of std::_Copy_impl<>
...
我将成员声明更改为
vector<unique_ptr<Bar>>* barList;
并编译。但我不禁想知道为什么我不能这样我最初想要的方式?对于咧嘴,我尝试这个,它工作正常:
And it compiles. But I can't help but wonder why I can't do it the way I originally wanted? For grins, I tried this and it works fine:
vector<Bar> barList;
但现在我失去了 unique_ptr
。我想要我的蛋糕,我也想吃它!
But now I lose the convenience of unique_ptr
. I want my cake and I want to eat it too!
推荐答案
这里的问题是, Foo
的复制赋值操作符。
The problem here is that somewhere, your code is attempting to call the "copy-assignment" operator of Foo
.
这会导致编译器尝试生成副本运算符,它调用 Foo
的所有子对象的复制赋值运算符。最终,这会导致尝试复制 unique_ptr
,这是不可能的操作。
This causes the compiler to attempt to generate a copy-assignment operator which calls the copy-assignment operators of all the subobjects of Foo
. Eventually, this leads to an attempt to copy a unique_ptr
, an operation which is not possible.
这篇关于如何声明一个unique_ptr的向量作为类数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!