Inserting a vector of unique_ptr into another vector

后端 未结 2 1572
名媛妹妹
名媛妹妹 2020-12-17 15:45

I have a vector of unique_ptr\'s and I want to append them to another vector of unique_ptrs. I would normally do a simple insert:

std::vector

        
相关标签:
2条回答
  • 2020-12-17 16:35

    unique_ptr is not assignable with normal assignment operator (the error says it's deleted). You can only move them:

    bar.insert(bar.end(),
        std::make_move_iterator(baz.begin()),
        std::make_move_iterator(baz.end())
    );
    

    Of course, this transfers the ownership of the managed object and original pointers will have nullptr value.

    0 讨论(0)
  • 2020-12-17 16:41

    You can't copy them; you'll have to move them.

    std::move(baz.begin(), baz.end(), std::back_inserter(bar));
    
    0 讨论(0)
提交回复
热议问题