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

前端 未结 13 2233
礼貌的吻别
礼貌的吻别 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

    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;.

提交回复
热议问题