devxlogo

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

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  Five Early Architecture Decisions That Quietly Get Expensive

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.