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

前端 未结 13 1850
礼貌的吻别
礼貌的吻别 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 06:49

    Yes, it can be expected at times. Whereas new reserves space for data, delete simply invalidates a pointer created with new, allowing data to be written at the previously reserved locations; it doesn't necessarily delete the data. However, you shouldn't rely on that behaviour because the data at those locations could change at any time, possibly causing your program to misbehave. This is why after you use delete on a pointer (or delete[] on an array allocated with new[]), you should assign NULL to it so that you can't tamper with an invalid pointer, assuming you won't allocate memory using new or new[] before using that pointer again.

提交回复
热议问题