why std::unique_ptr vector gets invalid pointer exception

后端 未结 2 359
轮回少年
轮回少年 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:05

    Your string is being destructed twice - once when your pv goes out of scope and is deleted, freeing all its contained unique_ptr elements, and once when s goes out of scope.

    To use a vector of unique pointers (or to use unique pointers in general), it is essential that they are not aliased. So you could write:

    auto *s = new std::string("str");
    pv.push_back(std::unique_ptr(s));
    // do not write "delete s" anywhere...
    

    Or, simpler and safer:

    pv.push_back(std::make_unique("str")); // make_unique is C++14
    

    Or even:

    std::unique_ptr p{new std::string("str")};
    pv.push_back(std::move(p));
    // Do not attempt to use p beyond this point.
    

提交回复
热议问题