2014-05-13 144 views
1

在初始化vectorunique_ptr时遇到一些问题。C++ 11 initializer list with 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 

所以我试图让移动构造函数来激活:

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 
+0

有[一种方法来做到这一点](http://stackoverflow.com/questions/8468774/can-i-list-initialize-a-vector-of-move-only-type/8469002#8469002),但它让我感到有些复杂。 – Edward

回答

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

用initialzer而不是构造函数创建unique_ptr。

相关问题