Reputation: 1203
I have to call a function of a class from another function of the same class. But the problem is for some cases the current object can be destroyed. So for this case calling the function is creating errors. Is there any way to check whether the current object is destroyed or not from inside the class?
Another thread may first delete the current object and then create another object of the same class before calling function1
from inside function2
. In that case, calling function1
would be valid, right?
For example,
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
using namespace std;
class example {
public:
example(){}
~example() {}
void function1() {
// some code here
return;
}
void function2() {
//some code here
// I want to check whether the current object is destroyed or not before calling function1()
function1();
}
private:
bool check;
};
int main()
{
example *exp=new example();
exp->function2();
}
Upvotes: 0
Views: 659
Reputation: 238351
Is there any way to check whether the current object is destroyed or not from inside the class?
No, there is no way to do that.
I presume that "from inside the class" means "by using state of the object". Well, if the object is destroyed, then there is no state that could be observed. Any attempt would result in undefined behaviour.
Also, when the object has been destroyed, member functions of the object may not be called, so it is pointless to test that in function2
because if the object had been destroyed, then calling function2
would already result in undefined behaviour.
Upvotes: 3