How do you move unique_ptr out of the vector <unique_ptr <Foo>>?
I would like to move unique_ptr<Foo>
from vector<unique_ptr<Foo>>
. Consider my code:
#include <vector>
#include <memory>
#include <iostream>
using namespace std;
class Foo {
public:
int x;
Foo(int x): x(x) {};
~Foo() {
cout << "Destroy of id: " << x << "\n";
x = -1;
};
};
int main(int argc, char *argv[]) {
auto foos = vector<unique_ptr<Foo>>();
foos.push_back(unique_ptr<Foo>(new Foo(100)));
foos.push_back(unique_ptr<Foo>(new Foo(101)));
foos.push_back(unique_ptr<Foo>(new Foo(102)));
// Print all
cout << "Vector size: " << foos.size() << "\n";
for (auto i = foos.begin(); i != foos.end(); ++i) {
cout << (*i)->x << "\n";
}
// Move Foo(100) out of the vector
{
auto local = move(foos.at(0));
cout << "Removed element: " << local->x << "\n";
}
// Print all! Fine right?
cout << "Vector size: " << foos.size() << "\n";
for (auto i = foos.begin(); i != foos.end(); ++i) {
cout << (*i)->x << "\n";
}
return 0;
}
I expected it to give:
Vector size: 3
100
101
102
Removed element: 100
Destroy of id: 100
Vector size: 2
101
102
But instead I get this result:
Vector size: 3
100
101
102
Removed element: 100
Destroy of id: 100
Vector size: 3
Segmentation fault: 11
Why is my vector size 3 and why am I getting segmentation error? How can I get the desired result?
source to share
Simplify your question to:
vector<unique_ptr<Foo>> foos;
foos.push_back(unique_ptr<Foo>(new Foo(100)));
auto local = std::move(foos[0]);
std::cout << foos[0]->x << '\n';
After creating local
, moving foos[0]
, foos[0]
no longer has the ownership of the pointer. It is empty. The expression is dereferenced, this becomes undefined behavior, which in your case manifests itself as a segmentation fault. At this point it is vector
perfectly "intact", it contains one empty unique_ptr
and is equivalent in state:
vector<unique_ptr<Foo>> foos(1);
You should just check that your unique_ptr
owns the pointer before dereferencing it:
if (foos[0]) {
// we wouldn't get here
std::cout << foos[0]->x << '\n';
}
Alternatively, since you want to apply the invariant to what yours vector
contains only valid pointers, only erase
this element should be as part of a branch operation from it :
auto local = std::move(foos[0]);
foos.erase(foos.begin());
// now foos is empty
source to share