Reputation: 1222
I got some weird problem. I use delete operator inside of class method and I want to know how solve this problem.
This is code:
#include <iostream>
using namespace std;
class A
{
public:
int a;
~A() {
cout << "call ~A()" << endl;
}
void action()
{
/* code here */
delete this; //this line depends on some if statements
/* code here */
}
void test2() {
cout << "call test2()" << a << endl;
}
void test() {
a = 10;
cout << "call test()" << endl;
action();
//how can I check if data is deleted?
test2();
}
};
int main()
{
A* a = new A();
a->test();
}
How can I check if data is deleted by delete operator? Is it even possible?
Upvotes: 0
Views: 941
Reputation: 10979
In C++ there are other return values available than void
. Therefore your action
can return something that indicates if this
has been deleted or not.
Note that you should not access any non-static data members or call any non-static member functions after deleteing this
. Some people feel it to be difficult to guarantee so they ban delete this
altogether.
Note to opponents that C++ FAQ claims that delete this
is legal construct and I haven't also found anything forbidding it.
Upvotes: 3
Reputation: 129374
Using delete this;
is nearly always "bad". There are exceptions, but those are really unusual. Think about what you are trying to do. Most of the time, this means that you should have a wrapper object and an inner object that is created/deleted by the wrapper object.
You can't check if something has been deleted (in a reliable way/portable way). In your particular test-case, you are exercising "undefined behaviour" by "using an object after it has been destroyed", which means you can't really tell what is going to happen. You have to trust the C++ runtime that delete
does what it says on the label.
Upvotes: 5