0

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.

Please teach me why this happen and how can I solve this.

rocambille
  • 15,398
  • 12
  • 50
  • 68
Bback.Jone
  • 61
  • 5
  • 4
    Where did you learn to write code that you make everything a pointer? There is almost never a good reason to have this type of problem. Also, the signature for the main method is incorrect; it always return an int. – Cody Gray - on strike Nov 30 '16 at 12:48
  • [“using namespace std” is considered bad practice?](http://stackoverflow.com/q/1452721/995714), and [`main` should return `int`](http://stackoverflow.com/q/204476/995714) – phuclv Nov 30 '16 at 13:14

2 Answers2

1

After you do m_List.erase(iter);, m_List is empty and **iter2 is undefined.
(*iter2 is the address of m_List's first element, which doesn't exist.)

It's very hard to say how to "solve this" because it's not clear what "this" is.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

It's because you erased it.

When you erased the element from m_list, you invalidate your previous &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.

Jason C
  • 38,729
  • 14
  • 126
  • 182