[英]How can I check whether double pointer that point dynamically allocated single pointer is NULL?
Please look at this code. 请看这段代码。
#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;
}
Result : 结果:
00000000
00A31A90
DDDDDDDD
00A31A90
&*iter
is equal to *iter2
, but *iter
is not equal to **iter2
. &*iter
等于*iter2
,但*iter
不等于**iter2
。
Please teach me why this happen and how can I solve this. 请教我为什么会这样以及如何解决这个问题。
After you do m_List.erase(iter);
执行
m_List.erase(iter);
, m_List
is empty and **iter2
is undefined. ,
m_List
为空,而**iter2
未定义。
( *iter2
is the address of m_List
's first element, which doesn't exist.) (
*iter2
是m_List
的第一个元素的地址,该地址不存在。)
It's very hard to say how to "solve this" because it's not clear what "this" is. 很难说如何“解决”这个问题,因为还不清楚“这个”是什么。
It's because you erased it. 这是因为您删除了它。
When you erased the element from m_list, you invalidate your previous &m_list.front(). 从m_list删除元素时,您先前的&m_list.front()无效。 All that's left is undefined garbage.
剩下的就是未定义的垃圾。
Don't erase it, and the results will be what you expect. 不要擦除它,结果将是您期望的。
But your mixing of pointers and lists and iterators is extremely obtuse and strange, you might want to see if there are ways to clean up your real code a bit. 但是,将指针,列表和迭代器混合在一起非常令人困惑和奇怪,您可能想看看是否有一些方法可以清理您的真实代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.