Question

I am trying to decide how many places in my code I want to put try/catch blocks.

I have the following functions.

void bar(BaseType* basePtr)
{
   DerivedType* dTypePtr = dynamic_cast<DerivedType*>(basePtr);
   if ( NULL != dTypePtr )
   {
      // Do stuff.
   }
}

void Controller::foo()
{    
   std::vector<BaseType*>::iterator iter = this->bList.begin();
   std::vector<BaseType*>::iterator end = this->bList.end();
   for ( ; iter != end; ++iter )
   {
      BaseType* basePtr = *iter;
      bool isObjectOK = true;

      // Check whether an object has been deleted without
      // notifying us.
      // If we can get the typeid of the object, chances are that
      // it has not been deleted.
      try
      {
         int const* typeName = typeid(*basePtr).name();
      }
      catch(...)
      {
         isObjectOK = false;
      }

      if ( isObjectOK )
      {
         bar(basePtr);
      }
   }
}

If I can successfully get a value from typeid(*basePtr).name(), can I safely assume that dynamic_cast<DerivedType*>(basePtr) will not throw an exception? If not, I have to modify bar to:

void bar(BaseType* basePtr)
{
   DerivedType* dTypePtr = NULL;
   try
   {
      dTypePtr = dynamic_cast<DerivedType*>(basePtr);
   }
   catch(...)
   {
      // Drop the exception.
   }

   if ( NULL != dTypePtr )
   {
      // Do stuff.
   }
}
Was it helpful?

Solution

If basePtr was a pointer to an object that has since been deleted, it is not "safe" or well-defined to do anything at all with that dangling pointer value. typeid(*basePtr) and dynamic_cast<T*>(basePtr) are both undefined behavior, meaning the situation is worse than causing an exception: your program could crash, could do the wrong thing, or could appear to work for years and then suddenly break.

If you need to know about destruction of objects, this sounds like a case for std::shared_ptr or std::weak_ptr. Ordinary code should not use new expressions or delete expressions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top