Why can I not push_back a unique_ptr into a vector?

后端 未结 2 1168
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 08:00

What is wrong with this program?

#include 
#include 

int main()
{
    std::vector> vec;

    in         


        
2条回答
  •  天涯浪人
    2020-11-22 08:36

    std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.

    error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
    e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
    eleter = std::default_delete, std::unique_ptr<_Tp, _Tp_Deleter> =
     std::unique_ptr]'
    

    The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

    The following works with the new emplace calls.

    std::vector< std::unique_ptr< int > > vec;
    vec.emplace_back( new int( 1984 ) );
    

    See using unique_ptr with standard library containers for further reading.

提交回复
热议问题