I asked a question:
Detecting if an object is still active or it has been destroyed
Considering that I cannot use libraries, there are no good out of the box solutions in C++. So, is it a bad practice to check if the object has been destroyed by analyzing memory where the deleted object resided, consider the code below:
#include <stdio.h>
class Foo {
public:
static unsigned int foo_id_gen; // unique id generator
unsigned int id;
int a;
Foo() {
++foo_id_gen;
if (foo_id_gen == 0) { // Handle rollover of unique ID
++foo_id_gen;
}
id = foo_id_gen; // Set unique ID
}
~Foo() {
id = 0; // Set unique ID to Zero
}
};
unsigned int Foo::foo_id_gen = 0;
class FooPtr {
public:
Foo* ptr;
unsigned int id;
explicit FooPtr(Foo* foo_obj_ptr) {
ptr = foo_obj_ptr;
id = foo_obj_ptr->id;
}
bool valid() {
return (ptr->id == id);
}
};
int main() {
Foo* A = new Foo;
FooPtr APtrOjb(A);
printf("Is valid?: %s\n", APtrOjb.valid() ? "Valid" : "Not Valid");
delete A;
printf("Is valid?: %s\n", APtrOjb.valid() ? "Valid" : "Not Valid");
}
When the object of class Foo is created, it gets a unique ID that can never be zero, when the object is deleted the destructor sets the unique ID to zero. Then the object of type FooPtr can check if the object of class Foo is still active by checking if the id's match.
Note: I realize that checking id does not 100% grantee the result since there is a small chance that a match can happen when the memory is alocated for other purposes. So lets assume that the id verification method can be strengthened to grantee 100% result, is this a viable solution?
Someone suggested that this question is similar to C++ delete - It deletes my objects but I can still access the data?, but his question is about deleting data, but my question is about detecting if object has been deleted.