从 typeid 成功返回是否保证dynamic_cast不会引发异常?

Does successful return from typeid guarantee that dynamic_cast won't throw an exception?

本文关键字:cast 异常 dynamic 成功 typeid 返回 是否      更新时间:2023-10-16

我想决定在我的代码中有多少地方我想放try/catch块

我有以下函数:

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);
      }
   }
}

如果我可以成功地从typeid(*basePtr).name()获得一个值,我可以安全地假设dynamic_cast<DerivedType*>(basePtr)不会抛出异常吗?如果没有,我必须修改bar为:

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

如果basePtr是指向一个已经被删除的对象的指针,那么使用该悬空指针值做任何事情都是不"安全"的或定义良好的。typeid(*basePtr)dynamic_cast<T*>(basePtr)都是未定义的行为,这意味着这种情况比引起异常更糟糕:你的程序可能崩溃,可能做错误的事情,或者可能看起来工作了几年,然后突然崩溃。

如果您需要了解对象的销毁,这听起来像是std::shared_ptrstd::weak_ptr的情况。普通代码不应使用new表达式或delete表达式