devxlogo

Use dynamic_cast to Detect a Deleted Pointer

Use dynamic_cast to Detect a Deleted Pointer

I found this out trying to work around a problem with an object shared across threads (yes, it was bad programming, but I still had to work around it). By casting to the base class before dynamic_cast, the deletion of the vtable is detected. If the object was no longer valid (deleted by the other thread) it became detectable:

#include using namespace std;class A{public:   A() {}   virtual ~A() {}};class B : public A{public:   B() {}};int main(){   B* pB =  new B;   cout ( pB) ";   cout (pB) ? "worked" : "failed") ( (A*)pB) ";   cout ( (A*)pB) ? "worked" : "failed") ( pB) ";   cout (pB) ? "worked" : "failed") ( (A*)pB) ";   cout ( (A*)pB) ? "worked" : "failed") ( pB) workeddynamic_cast( (A*)pB) workeddynamic_cast( pB) workeddynamic_cast( (A*)pB) failed

devx-admin

Share the Post: