[英]How can I check whether double pointer that point dynamically allocated single pointer is NULL?
请看这段代码。
#include <iostream>
#include <list>
using namespace std;
void main()
{
list<int*> m_List;
int* i = new int(1);
m_List.push_back(i);
list<int**> m_pList;
m_pList.push_back(&m_List.front());
list<int*>::iterator iter = m_List.begin();
delete *iter;
*iter = NULL;
cout << *iter << endl;
cout << &*iter << endl;
iter = m_List.erase(iter);
list<int**>::iterator iter2 = m_pList.begin();
cout << **iter2 << endl;
cout << *iter2 << endl;
}
结果:
00000000
00A31A90
DDDDDDDD
00A31A90
&*iter
等于*iter2
,但*iter
不等于**iter2
。
请教我为什么会这样以及如何解决这个问题。
执行m_List.erase(iter);
, m_List
为空,而**iter2
未定义。
( *iter2
是m_List
的第一个元素的地址,该地址不存在。)
很难说如何“解决”这个问题,因为还不清楚“这个”是什么。
这是因为您删除了它。
从m_list删除元素时,您先前的&m_list.front()无效。 剩下的就是未定义的垃圾。
不要擦除它,结果将是您期望的。
但是,将指针,列表和迭代器混合在一起非常令人困惑和奇怪,您可能想看看是否有一些方法可以清理您的真实代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.