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 << "dynamic_cast( pB) ";   cout << ( dynamic_cast(pB) ? "worked" : "failed") << endl;     cout << "dynamic_cast( (A*)pB) ";   cout << ( dynamic_cast( (A*)pB) ? "worked" : "failed") << endl;     delete pB;       cout << "dynamic_cast( pB) ";   cout << ( dynamic_cast(pB) ? "worked" : "failed") << endl;     cout << "dynamic_cast( (A*)pB) ";   cout << ( dynamic_cast( (A*)pB) ? "worked" : "failed") << endl;     }the output:dynamic_cast( pB) workeddynamic_cast( (A*)pB) workeddynamic_cast( pB) workeddynamic_cast( (A*)pB) failed
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: