1
在初始化vector
的unique_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
有[一种方法来做到这一点](http://stackoverflow.com/questions/8468774/can-i-list-initialize-a-vector-of-move-only-type/8469002#8469002),但它让我感到有些复杂。 – Edward