从 typeid 成功返回是否保证dynamic_cast不会引发异常?
Does successful return from typeid guarantee that dynamic_cast won't throw an exception?
我想决定在我的代码中有多少地方我想放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_ptr
或std::weak_ptr
的情况。普通代码不应使用new表达式或delete表达式
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- 如何理解C++标准N3337中的expr.const.cast子句8
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- C++Cast运算符过载
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?