why std::unique_ptr vector gets invalid pointer exception

坚强是说给别人听的谎言 提交于 2019-12-02 04:14:22

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<std::string> vector;
vector.emplace_back("str");
std::cout << pv[0] << std::endl;

There's no need for std::unique_ptr<std::string> there.

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<std::string>(s));
// do not write "delete s" anywhere...

Or, simpler and safer:

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

Or even:

std::unique_ptr<std::string> p{new std::string("str")};
pv.push_back(std::move(p));
// Do not attempt to use p beyond this point.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!