why std::unique_ptr vector gets invalid pointer exception

后端 未结 2 379
轮回少年
轮回少年 2021-01-24 21:44

I wrote simple code to help me understand smart pointers:

string s = \"str\";
vector > pv ;

pv.push_back(unique_ptr         


        
2条回答
  •  無奈伤痛
    2021-01-24 22:03

    In the std::unique_ptr's destructor it will call delete on the &s pointer which was not allocated via new.

    Just use:

    std::vector vector;
    vector.emplace_back("str");
    std::cout << pv[0] << std::endl;
    

    There's no need for std::unique_ptr there.

提交回复
热议问题