Deleting C++ pointers to an object

前端 未结 9 1183
攒了一身酷
攒了一身酷 2021-01-26 20:06

I thought that the delete command would free up memory I allocated. Can someone explain why it seems I still have the memory in use after delete?

class Test
{
pu         


        
相关标签:
9条回答
  • 2021-01-26 20:41

    The reason that doesn't break in your tests is a combination of luck and the fact that you have a very simple, very short routine. You're addressing memory still in your process' space and you have so few instructions, the routine probably runs in one shot.

    The delete keyword de-allocates the memory in the process' memory manager, but it doesn't clear it out or (usually) touch it much at all. If the memory is later used, the values will change, but until then, whatever you last set it to will stick around (more or less, this is undefined after all).

    Considering the fact your routine has only a few instructions, chances are high that the processor is executing them sequentially, without changing to another process in between. This has the side effect that nothing else is likely to overwrite your memory or allocate it, so the memory remains in the process' space.

    Because it is used again so quickly, the values you left are (likely to be) still there and it is unlikely to be in use by another process.

    0 讨论(0)
  • 2021-01-26 20:43

    Undefined behavior is just that, undefined. It can even work if it so pleases.

    0 讨论(0)
  • 2021-01-26 20:45

    Accessing deleted object is an undefined behavior. Anything can happen

    0 讨论(0)
提交回复
热议问题