Possible Duplicate:
C++: Delete this?
In C++, is it ok to delete the self object in function definition. What are side effects of this?
class MyClass {
public:
void ~myClass() {}
void myFunction() {
// logic here
delete this;
}
}
Thanks!
A self-destruct is a mechanism that can cause an object to destroy itself or render itself inoperable after a predefined set of circumstances has occurred. Self-destruct mechanisms are typically found on devices and systems where malfunction could endanger large numbers of people.
No. Just no! Allocate the dialog to the stack and make ui a smart pointer ( std::unique_ptr ). As a side note, normally dialogs are closed by calling either accept() or reject() not by deleting itself.
A class declaration can contain static object of self type, it can also have pointer to self type, but it cannot have a non-static object of self type. For example, following program works fine.
Conclusion: In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak.
From parashift FAQ:
Is it legal (and moral) for a member function to say delete this?
As long as you're careful, it's OK for an object to commit suicide (delete this).
Here's how I define "careful":
You must be absolutely 100% positively sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).
You must be absolutely 100% positively sure that your member function will be the last member function invoked on this object.
You must be absolutely 100% positively sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).
Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class when you don't have a virtual destructor.
You may delete an object from within itself, but it is necessary that you do not, afterward, access any member variables or functions of that class instance after doing so.
It's pretty dangerous. Consider this:
void foo() {
MyClass bar;
bar.myFunction(); // calls delete
} // bar goes out of scope, calls delete again
Check out this C++FAQ 16.15 entry for when doing delete this
is possible - it's legal, just needs to be used bery carefully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With