Why can I not push_back a unique_ptr into a vector?

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

What is wrong with this program?

#include 
#include 

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

    in         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 08:24

    You need to move the unique_ptr:

    vec.push_back(std::move(ptr2x));
    

    unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.

    Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:

    std::unique_ptr ptr(new int(1));
    

提交回复
热议问题