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

Solution 1:

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

This is technically known as Undefined Behavior. Don't be surprised if it offers you a can of beer either.

Solution 2:

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.

Solution 3:

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