Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a vector of unique_ptr's as class data member?

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!

like image 985
Bret Kuhns Avatar asked Jan 24 '12 14:01

Bret Kuhns


People also ask

Can you move unique_ptr?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.

What is a unique_ptr in C++?

(since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope.

What is the scope of unique_ptr?

An​ unique_ptr has exclusive ownership of the object it points to and ​will destroy the object when the pointer goes out of scope. A unique_ptr explicitly prevents copying of its contained pointer.

Why should you use unique_ptr?

std::unique_ptr represents data which has only one owner at any given time. It should be your default choice when you need a smart pointer. You can move a std::unique_ptr around to keep it alive, but there can only be one owner of the data. After moving the pointer, the previous pointer object is invalidated.


2 Answers

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

like image 82
Sonic78 Avatar answered Oct 12 '22 23:10

Sonic78


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.

like image 23
Mark B Avatar answered Oct 13 '22 00:10

Mark B