问题
I wrote simple code to help me understand smart pointers:
string s = "str";
vector <unique_ptr<string>> pv ;
pv.push_back(unique_ptr<string>(&s));
cout<<*(pv[0])<<endl;
This code compiles fine, but gets me a runtime error:
str * Error in `...': munmap_chunk(): invalid pointer: 0x00007ffd956e57e0 * Aborted (core dumped)
What happened and what have I done wrong?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/32357344/why-stdunique-ptr-vector-gets-invalid-pointer-exception