C++ delete - It deletes my objects but I can still access the data?

前端 未结 13 1879
礼貌的吻别
礼貌的吻别 2020-11-21 06:11

I have written a simple, working tetris game with each block as an instance of a class singleblock.

class SingleBlock
{
    public:
    SingleBlock(int, int)         


        
相关标签:
13条回答
  • 2020-11-21 07:01

    Is being able to access data from beyond the grave expected?

    In most cases, yes. Calling delete doesn't zero the memory.

    Note that the behavior is not defined. Using certain compilers, the memory may be zeroed. When you call delete, what happens is that the memory is marked as available, so the next time someone does new, the memory may be used.

    If you think about it, it's logical - when you tell the compiler that you are no longer interested in the memory (using delete), why should the computer spend time on zeroing it.

    0 讨论(0)
  • 2020-11-21 07:01

    Delete doesn't delete anything -- it just marks the memory as "being free for reuse". Until some other allocation call reserves and fills that space it will have the old data. However, relying on that is a big no-no, basically if you delete something forget about it.

    One of the practices in this regard that is often encountered in libraries is a Delete function:

    template< class T > void Delete( T*& pointer )
    {
        delete pointer;
        pointer = NULL;
    }
    

    This prevents us from accidentally accessing invalid memory.

    Note that it is perfectly okay to call delete NULL;.

    0 讨论(0)
  • 2020-11-21 07:02

    It will lead to undefined behaviour and delete deallocates memory , it does not reinitialize it with zero .

    If you want to make it zero out then do :

    SingleBlock::~SingleBlock()
    
    {    x = y = 0 ; }
    
    0 讨论(0)
  • 2020-11-21 07:04

    delete deallocates the memory, but does not modify it or zero it out. Still you should not access deallocated memory.

    0 讨论(0)
  • 2020-11-21 07:07

    Heap memory is like a bunch of blackboards. Imagine you are a teacher. While you're teaching your class, the blackboard belongs to you, and you can do whatever you want to do with it. You can scribble on it and overwrite stuff as you wish.

    When the class is over and you are about to leave the room, there is no policy that requires you to erase the blackboard -- you simply hand the blackboard off to the next teacher who will generally be able to see what you wrote down.

    0 讨论(0)
  • 2020-11-21 07:10

    It is what C++ calls undefined behaviour - you might be able to access the data, you might not. In any case, it is the wrong thing to do.

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