Introduction to Programming and C++

Contents Previous Topic Next Topic

Recall that this is simply a pointer to the current object, so that when a member function is called, you have access to the original object.

Because this is just the address of the object, there is no reason that, if you are aware that the object was created with new that you cannot call

	delete this;
	// this = 0;   can't do this....

However, unlike previous warnings to always assign a pointer to 0 if it was deleted, because this is declared to be const, you cannot reassign it. Even if you were able to reassign to this, that would not affect the value of the original variable. In Program 1, the object allocated using new is deleted when remove() is called, however, the original pointer is still pointing to that memory location.

Program 1. Deleting this.

#include <iostream>

using namespace std;

class Simple {
	public:
		int x;

		void remove() {
			delete this;
		}
};

int main() {
	Simple * var = new Simple;

	cout << "The address stored by 'var' is " << var << endl;

	var -> x = 5;

	var -> remove();

	cout << "The address stored by 'var' is (still) " << var << endl;
	var = 0;  // better to be safe...

	return 0;
}

When we discuss binary search trees, we will see how we can successfully delete this and remove all references to the now-freed memory.

One question you may have is, what happens if you try to delete memory which was not assigned using new? Program 2 demonstrates how this could potentially happen. Recall that the memory for var was allocated by the compiler, and now, you are indicating to the operating system that that memory is now free for any other program to use. Unfortunately, the compiler is very likely expecting to be able to use that memory again.

Program 2. Invalid deletion of this.

class Simple {
	public:
		int x;

		void remove() {
			delete this;
		}
};

int main() {
	Simple var;

	var.x = 5;

	var.remove(); // dangerous

	return 0;
}

Questions

1. I'll think of some...


Contents Previous Topic Top Next Topic