不会删除std :: list :: iterator使迭代器无效并破坏该对象吗? [英] Doesn't erasing std::list::iterator invalidates the iterator and destroys the object?

查看:69
本文介绍了不会删除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;

我知道 erase 会返回什么,但是我想知道为什么这可以吗?还是未定义,还是取决于编译器?

I know what erase returns, but I wonder why this is OK? Or is it undefined, or does it depend on the compiler?

推荐答案

是的,这是不确定的行为.您正在取消引用一种野指针.在 erase 之后,您不应使用 i 的值.

Yes, it's undefined behaviour. You are dereferencing a kind of wild pointer. You shouldn't use the value of i after erase.

是的,擦除 破坏指向的对象.但是,对于POD类型,销毁没有任何作用.

And yes, erase destructs the object pointed to. However, for POD types destruction doesn't do anything.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆