Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I not try to use "this" value after "delete this"?

In this paragraph of C++ FAQ usage of delete this construct is discussed. 4 restrictions are listed.

Restrictions 1 to 3 look quite reasonable. But why is restriction 4 there that I "must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it"?

I mean this is yet another pointer. Why can't I reinterpret_cast it to an int or call printf() to output its value?

like image 207
sharptooth Avatar asked Dec 08 '09 11:12

sharptooth


People also ask

What happens when you delete C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.

What is the effect of using delete for NULL pointer?

What happens when delete is used for a NULL pointer? Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.

What happens when you delete an object?

You can remove one or more objects using the delete operation. The Delete operation permanently removes the selected object from the database. To remove an object without deleting it, use Cut.

Can we use delete instead of free?

Differences between delete and free() The delete operator is used to delete the pointer, which is either allocated using new operator or a NULL pointer, whereas the free() function is used to delete the pointer that is either allocated using malloc(), calloc() or realloc() function or NULL pointer.


2 Answers

The value of 'this' after calling delete is undefined, and the behaviour of anything you do with it is also undefined. While I would expect most compilers to do something sensible, there's nothing (in the spec) stopping the compiler from deciding that its behaviour in this particular case will be emit code to format your hard-disk. Invoking undefined behaviour is (almost) always a mistake, even when your particular compiler behaves in the way you'd like it to.

You could work around this by taking a copy of the pointer (as an integer) before calling delete.

like image 112
Andrew Aylett Avatar answered Oct 03 '22 07:10

Andrew Aylett


The reason that you cannot do anything with a pointer after you delete it (this, or any other pointer), is that the hardware could (and some older machines did) trap trying to load an invalid memory address into a register. Even though it may be fine on all modern hardware, the standard says that the only thing that you can do to a invalid pointer (uninitialized or deleted), is to assign to it (either NULL, or from another valid pointer).

like image 31
KeithB Avatar answered Oct 03 '22 06:10

KeithB