C++ deleting a pointer when there are 2 pointers pointing to the same memory locations

后端 未结 4 1898
既然无缘
既然无缘 2020-12-17 07:26

Lets say, I have one pointer

int *l1 = new int[100*100];

int *l2 = l1;

Now, l1 & l2 both point to the same sequ

4条回答
  •  时光说笑
    2020-12-17 07:59

    Here's an analogy which may help you understand.

    A pointer is like the address of an apartment building.

    Many people may have the address of the same building.

    If one of them changes the array (think of renovating the building) everyone will see it as they are all looking at the same thing.

    When you 'delete' the array you mark the apartment building as condemned and available for re-development.

    Many people may continue to have the address of the now condemned building after it is deleted.

    If they reference the array after it's deleted (the building was condemned) it may, or may not, still be present. It depends on if the city got around to demolishing the condemned building. It's not safe to do but there's nothing preventing you from doing it. Sometimes you get lucky and the building is still there. Sometimes you'll find something new was built in that place. Sometimes the building falls down on you.

提交回复
热议问题