How to declare a vector of unique_ptr's as cla

2020-07-06 06:17发布

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;
}

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>'

Along with a handful of error lines below that which dive into Microsoft's implementation of std::_Copy_impl<>...

I changed the member declaration to

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;

But now I lose the convenience of unique_ptr. I want my cake and I want to eat it too!

5条回答
Melony?
2楼-- · 2020-07-06 06:39

The problem here is that somewhere, your code is attempting to call the "copy-assignment" operator of Foo.

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.

查看更多
ら.Afraid
3楼-- · 2020-07-06 06:48

unique_ptr doesn't have copy semantics, so you can't use any methods that would copy the contained object. You can do this with rvalue references by using std::move in the place(s) it's trying to make a copy. Without seeing your code I can't say where that would be.

If it compiles in the second form either you didn't exercise the same code or there's a compiler bug. Both should fail the same way.

Your third example, storing by value is the simplest way unless your objects are large and expensive to store/copy around by value.

查看更多
smile是对你的礼貌
4楼-- · 2020-07-06 06:49

An excerpts from www.cplusplus.com

std::unique_ptr::operator=

unique_ptr assignment The object acquires the ownership of x's content, including both the stored pointer and the stored deleter (along with the responsibility of deleting the object at some point). Any object owned by the unique_ptr object before the call is deleted (as if unique_ptr's destructor was called).

But there is a warning too:

This page describes a feature introduced by the latest revision of the C++ standard (2011). Older compilers may not support it.

MSVC 2010 defines operator= as private (non-copyable) but supports swap method.

查看更多
我只想做你的唯一
5楼-- · 2020-07-06 06:49

You can't use unique_ptr in vector because vector implementation strongly relies on values assign operator, which is private in unique_ptr. Use shared_ptr from boost or other smart ptr implementation from C++11.

查看更多
一纸荒年 Trace。
6楼-- · 2020-07-06 07:04

Often a std::move(iUniquePtr) is missing somewhere (e. g. when using push_back).

查看更多
登录 后发表回答