不擦除std :: list :: iterator使迭代器无效并销毁对象? [英] Doesn't erasing std::list::iterator invalidates the iterator and destroys the object?
本文介绍了不擦除std :: list :: iterator使迭代器无效并销毁对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么以下列出 2
?
list<int> l;
l.push_back( 1 );
l.push_back( 2 );
l.push_back( 3 );
list<int>::iterator i = l.begin();
i++;
l.erase( i );
cout << *i;
我知道如何清除
奇怪为什么这是好吗?或者是未定义的,还是依赖于编译器?
I know what erase
returns, but I wonder why this is OK? Or is it undefined, or does it depend on the compiler?
推荐答案
是的,它是未定义的行为。你是解引用一种野生指针。在擦除后,不应使用
i
的值。
Yes, it's undefined behaviour. You are dereferencing a kind of wild pointer. You shouldn't use the value of i
after erase
.
是,清除
毁损对象指向。
擦除
不会分配任何特殊的null值到被删除的迭代器,迭代器只是不再有效。
erase
doesn't assign any special "null" value to the iterator being erased, the iterator is just not valid any more.
这篇关于不擦除std :: list :: iterator使迭代器无效并销毁对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文