2

Having some issues getting the syntax correct for initializing a vector of unique_ptr.

class Thing
{};
class Spider: public Thing
{};

Initially tried:

std::vector<std::unique_ptr<Thing>>  stuff{std::unique_ptr<Thing>(new Spider)};

But this requires copy constructor (which unique_ptr does not have).

game.cpp:62:46: note: in instantiation of member function 'std::__1::vector<std::__1::unique_ptr<Thing, std::__1::default_delete<Thing> >, std::__1::allocator<std::__1::unique_ptr<Thing, std::__1::default_delete<Thing> > > >::vector' requested here
        std::vector<std::unique_ptr<Thing>>  WestOfStartThings{std::unique_ptr<Thing>(new Spider)};
                                             ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:2510:31: note: copy constructor is implicitly deleted because 'unique_ptr<Thing, std::__1::default_delete<Thing> >' has a user-declared move constructor
    _LIBCPP_INLINE_VISIBILITY unique_ptr(unique_ptr&& __u) _NOEXCEPT

So I tried to get the move constructor to activate:

std::vector<std::unique_ptr<Thing>>  WestOfStartThings{std::move(std::unique_ptr<Thing>(new Spider))};

But still no luck.

game.cpp:62:46: note: in instantiation of member function 'std::__1::vector<std::__1::unique_ptr<Thing, std::__1::default_delete<Thing> >, std::__1::allocator<std::__1::unique_ptr<Thing, std::__1::default_delete<Thing> > > >::vector' requested here
        std::vector<std::unique_ptr<Thing>>  WestOfStartThings{std::move(std::unique_ptr<Thing>(new Spider))};
                                             ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/memory:2510:31: note: copy constructor is implicitly deleted because 'unique_ptr<Thing, std::__1::default_delete<Thing> >' has a user-declared move constructor
    _LIBCPP_INLINE_VISIBILITY unique_ptr(unique_ptr&& __u) _NOEXCEPT
Edward
  • 6,964
  • 2
  • 29
  • 55
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • There's [a way to do this](http://stackoverflow.com/questions/8468774/can-i-list-initialize-a-vector-of-move-only-type/8469002#8469002) but it strikes me as a bit convoluted. – Edward May 13 '14 at 17:53

1 Answers1

0

Do you care particularly about using initializer lists?

If your goal is just to create the vector above, you can use the following syntax:

std::vector<std::unique_ptr<Thing>>  WestOfStartThings;
WestOfStartThing.emplace_back(new Spider);

If you do want to use the initializer lists specifically, I believe the syntax is:

std::vector<std::unique_ptr<Thing>>  stuff{std::unique_ptr<Thing>{new Spider}};

creating the unique_ptr with an initializer rather than the constructor.

Tim Sylvester
  • 22,897
  • 2
  • 80
  • 94
patros
  • 7,719
  • 3
  • 28
  • 37