When you delete a pointer, you free the memory allocated to the pointer, created in a heap, i.e., dynamically. You can't delete anything not created by new
or new[]
.
The name remains (unless the {braces} force it to expire) and you will be able to use it again and will not be able to use it otherwise.
Consider this code:
int * pointer = new int; // a pointer created;
*pointer = 1;//memory holds the value 1
std::cout << "Value: " << *pointer << ", Location: " << pointer << std::endl;
delete pointer;// pointer's memory is not used by the pointer
pointer = new int;
*pointer = 2;//memory holds the value 2
std::cout << "Value: " << *pointer << ", Location: " << pointer << std::endl;
delete pointer;// pointer's memory is not used by the pointer
Location can be the same or change (they would more likely change if in between the allocations you'd place any other allocation). This is heap, it doesn't really matter where it is stored. Try compiling it (inside int main(){}
) and see yourself the locations on your machine.
When you assign something to a pointer, you tell him where to point to.
This is different.
Basically, assigning a nullptr
is what you need, so it shouldn't even be called a deletion. However, a pointer can well stay without any value to point unless you will try deleting it. And because deleting twice brings to undefined behavior, it should point to someplace, deletion of which will bring no harm.
In some circumstances, you create a program that deletes the memory pointed to by a pointer in any case and you won't check if the memory is allocated or deleted. (The most common example, perhaps, is move semantics.) Therefore, a nullpointer is always used there, as a part of a pattern.
Concerning NULL
: macros become more and more obsolete in C++ as it moves towards freedom. It can bring to artifacts, so don't mess with it and make your life easier.