我想将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