What does deleting a pointer mean?
Yes, delete
is used to deallocate memory and call the destructor for the object involved.
It's common pratice to set pointer to NULL
after deleting it to avoid having invalid pointers around:
Object *o = new Object();
// use object
delete o; // call o->~Object(), then releases memory
o = NULL;
When new
and delete
are used with standard C types in C++ source they behave like malloc
and free
.
Deleting a pointer (or deleting what it points to, alternatively) means
delete p;
delete[] p; // for arrays
p
was allocated prior to that statement like
p = new type;
It may also refer to using other ways of dynamic memory management, like free
free(p);
which was previously allocated using malloc
or calloc
p = malloc(size);
The latter is more often referred to as "freeing", while the former is more often called "deleting". delete
is used for classes with a destructor since delete
will call the destructor in addition to freeing the memory. free
(and malloc
, calloc
etc) is used for basic types, but in C++ new
and delete
can be used for them likewise, so there isn't much reason to use malloc
in C++, except for compatibility reasons.
You can't "delete" a pointer variable, only set their value to NULL (or 0).
You can't "delete" a pointer variable
Sure you can ;-)
int** p = new int*(new int(42));
delete *p;
delete p; // <--- deletes a pointer
But seriously, delete
should really be called delete_what_the_following_pointer_points_to
.