Deleting a pointer in C++

后端 未结 6 1352
旧巷少年郎
旧巷少年郎 2020-11-28 01:11

Context: I\'m trying to wrap my head around pointers, we just saw them a couple of weeks ago in school and while practicing today I ran into a silly? issue, it can be super

6条回答
  •  -上瘾入骨i
    2020-11-28 01:59

    There is a rule in C++, for every new there is a delete.

    1. Why won't the first case work? Seems the most straightforward use to use and delete a pointer? The error says the memory wasn't allocated but 'cout' returned an address.

    new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:

    myPointer = &myVar;
    

    you say:

    myPointer = The address of where the data in myVar is stored

    1. On the second example the error is not being triggered but doing a cout of the value of myPointer still returns a memory address?

    It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.

    1. Does #3 really work? Seems to work to me, the pointer is no longer storing an address, is this the proper way to delete a pointer?

    NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:

    myPointer = NULL;
    

    which equals:

    myPointer = 0;
    

提交回复
热议问题