I have written a simple, working tetris game with each block as an instance of a class singleblock.
class SingleBlock
{
public:
SingleBlock(int, int)
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.
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;
.
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 ; }
delete deallocates the memory, but does not modify it or zero it out. Still you should not access deallocated memory.
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.
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.