【发布时间】:2019-09-21 20:15:24
【问题描述】:
请尝试编译并运行以下代码。
当迭代共享指针向量时,我必须删除最后一个元素,这将导致分段错误,但我不明白为什么for 迭代在el_it 达到v.end() 时不会中断,并且我必须手动完成(注释代码)。
#include <vector>
using std::vector;
#include <memory>
using std::shared_ptr;
#include <algorithm>
using std::remove;
class A {
public:
A(int age) { age_ = age; }
int age_ = 0;
int alive_ = 1;
};
int main() {
shared_ptr<A> a0(new A(0));
shared_ptr<A> a1(new A(1));
shared_ptr<A> a2(new A(2));
vector< shared_ptr <A> > v;
v.push_back(a0);
v.insert(v.end(), a1);
v.insert(v.end(), a2);
for (auto el_it = v.begin(); el_it != v.end(); ++ el_it) {
auto el = *el_it;
if (el->age_ == 2) {
v.erase(el_it);
}
/*
if (el_it == v.end()) // Why is this required ??
break;
*/
}
return 0;
}
【问题讨论】:
-
与Iterator invalidation rules相关且可能重复
-
"
if (el_it == v.end()) // Why is this required ??",其实没有,还有UB。 -
@P.W 耶! #keepduping
-
@LightnessRacesinOrbit: :-)。最近没有任何添加到 C++faq 标签中。有任何贡献吗?
标签: c++ vector shared-ptr