Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
May 17, 2005

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 <iostream>

using namespace std;

class A
{
public:
   A() {}
   virtual ~A() {}
};

class B : public A
{
public:
   B() {}
};

int main()
{
   B* pB =  new B;

   cout << "dynamic_cast<B*>( pB) ";
   cout << ( dynamic_cast<B*>(pB) ? "worked" : "failed") << endl;  

   cout << "dynamic_cast<B*>( (A*)pB) ";
   cout << ( dynamic_cast<B*>( (A*)pB) ? "worked" : "failed") << endl;  

   delete pB; 
   
   cout << "dynamic_cast<B*>( pB) ";
   cout << ( dynamic_cast<B*>(pB) ? "worked" : "failed") << endl;  

   cout << "dynamic_cast<B*>( (A*)pB) ";
   cout << ( dynamic_cast<B*>( (A*)pB) ? "worked" : "failed") << endl;  
   
}

the output:
dynamic_cast<B*>( pB) worked
dynamic_cast<B*>( (A*)pB) worked
dynamic_cast<B*>( pB) worked
dynamic_cast<B*>( (A*)pB) failed
Rick Brown
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date