To test your C++ programming experience and curiosity, a pop quiz question could be : what can you say about the C++ expression "delete this"?
In C++, "this" keyword is used in object member functions and is a pointer to the curent object.
As a beginner, the answer seemed to be obvious to me: how the language can allow an object to commit suicide? Impossible, I thought.
However, it's possible to "delete this". Deleting the current object does not cause compilation errors. Although "delete this" is accepted by compilation, its usage can lead to logic errors. Indeed, if this suicide is absolutely necessary, the following rules must be observed:
1. The object must be created via dynamic allocation using new operator.
2. No member function of the object is invoked on "this" object after suicide.
3. No member object of "this" object is called after suicide.
4. Nothing will use "this" object after suicide.
PS: I once tried to violate rule #3, and the result was not surprising: Wonderful Death Blue Screen crash followed by an automatic restart! Nice!
In C++, "this" keyword is used in object member functions and is a pointer to the curent object.
As a beginner, the answer seemed to be obvious to me: how the language can allow an object to commit suicide? Impossible, I thought.
However, it's possible to "delete this". Deleting the current object does not cause compilation errors. Although "delete this" is accepted by compilation, its usage can lead to logic errors. Indeed, if this suicide is absolutely necessary, the following rules must be observed:
1. The object must be created via dynamic allocation using new operator.
2. No member function of the object is invoked on "this" object after suicide.
3. No member object of "this" object is called after suicide.
4. Nothing will use "this" object after suicide.
PS: I once tried to violate rule #3, and the result was not surprising: Wonderful Death Blue Screen crash followed by an automatic restart! Nice!
Commentaires