Skip to the content of the web site.

Lesson 206: Can you delete this?

Previous lesson Next lesson


Suppose you had a class with a member function erase() that called delete this;:

// Delete_class.h
#pragma once
class Delete_class;

class Delete_class {
	public:
		Delete_class( int n = 0.0 );
		void erase();

	private:
		int datum;
};
// Delete_class.cpp
#include <iostream>
#include "Delete_class.h"

Delete_class::Delete_class( int n ):
datum( n ) {
	// Empty constructor
}

void Delete_class::erase() {
	delete this;
}

If you compile and execute this program:

#include "Delete_class.h"
int main();

int main() {
	Delete_class *p_info= new Delete_class{42};
	p_info->erase();

	return 0;
}

everything appears to function correctly. Indeed, everything will function correctly, for the memory for the object was allocated dynamically, and p_info is simply storing the address of that memory that allocated by the operating system. Consequently, when you call erase(), this is simply assigned that memory location, so when delete this; is called, it indicates to the operating system that the memory at that location is no longer required. If no subsequent access is made to anything associated with the object, there should be no further issues.

The requirements for being able to call delete this; include:

  1. The object on which erase() is called must have been dynamically allocated using the new command:
    • For example, the object on which erase() cannot be one where the instance is a local variable, so
      Delete_class info{32};
      info.erase();

      would be forbidden.
    • Similarly, the object cannot be allocated as part of an array, so
      Delete_class *a_info = new Delete_class[32];
      a_info[15].erase();

      would similarly be forbidden.
  2. You must ensure that no member variable in the object is ever accessed again after the erase() member function is called, not even after the delete this; statement inside the erase() member function.

Unfortunately, there is no way that the constructor can be made aware as to whether or not the object on which the constructor is being called is through dynamic or static memory allocation. Thus, this can really only be used if the programmer is guaranteed that the objects will always be dynamically allocated; for example, as nodes in a linked list or a tree.


Previous lesson Next lesson