我想移动一个
我预计这会带来以下结果:
但是实际上,我得到了这个结果:
为什么我的向量大小仍然是3,为什么会出现分段错误?我该如何得到我想要的结果?
unique_ptr<Foo>
出一个 vector<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,为什么会出现分段错误?我该如何得到我想要的结果?
nullptr
)。尝试对其进行解引用是未定义行为。这与在vector<int*> v;
中执行v[0] = nullptr
并尝试解引用*v[0]
没有区别。行为是一致的,std::move
没有问题,向量也没有“损坏”,它应该是这样的。你唯一的机会是重新分配向量,但在这种情况下,你可以直接复制。 - vsoftco