带有unique_ptr的C ++ 11初始化列表

时间:2014-05-13 17:26:04

标签: c++11 vector initialization unique-ptr

在初始化vector unique_ptr时,有一些问题可以使语法正确。

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

最初尝试过:

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

但这需要复制构造函数(unique_ptr没有)。

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

所以我试着让move构造函数激活:

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

但仍然没有运气。

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

1 个答案:

答案 0 :(得分:0)

您是否特别关注使用初始化程序列表?

如果您的目标只是创建上面的向量,则可以使用以下语法:

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

如果您确实想要专门使用初始化列表,我相信语法是:

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

使用初始化器而不是构造函数创建unique_ptr。