我想將unique_ptr<Foo>
從vector<unique_ptr<Foo>>
中移出。想想我的代碼:如何將unique_ptr移出載體<unique_ptr <Foo>>?
#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;
}
我預計這將產生:
Vector size: 3
100
101
102
Removed element: 100
Destroy of id: 100
Vector size: 2
101
102
但是,相反,我得到這樣的結果:
Vector size: 3
100
101
102
Removed element: 100
Destroy of id: 100
Vector size: 3
Segmentation fault: 11
爲什麼我的矢量大小還是3,爲什麼我是否收到分段錯誤?我怎樣才能得到我想要的結果?
矢量沒有壞掉。您可以在解除引用之前檢查unique_ptr。但你選擇不要。 – juanchopanza
@juanchopanza我已經清楚地發佈了我想要的輸出結果。你還想要什麼? – Doug
根據你所說的,你不想移動任何東西,你只是想複製 – AndyG