使用dynamic_cast转换指针时抛出bad_cast?
如果您强制转换引用,dynamic_cast 会抛出 bad_cast
异常,但据我所知,标准指针被视为引用,即指针是引用的类型。
那么在转换指针时我应该得到 bad_cast 吗?
这个问题是由此页面的try-catch块引起的。这个 try-catch 块不合适吗?
dynamic_cast throws bad_cast
exception if you cast a reference but as I know in the standard pointers are considered as references, i.e. a pointer is a type of a reference.
So should I get bad_cast when casting pointers?
This question arose from the try-catch block from this page. Is this try-catch block inappropriate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
否,如果出现错误的转换,
dynamic_cast
将返回null
。另外,dynamic_cast仅适用于多态类,因此,如果您正在谈论内置数据类型(来自问题中的链接),那么您应该使用
static_cast
。顺便说一句,引用不是指针。
No with pointers in case of a bad cast,
dynamic_cast
will return anull
.Also, dynamic_cast works only on Polymorphic classes, So if you are talking about built in data types(from the link in your question) then
static_cast
is what you should be using.And btw, References are NOT pointers.
关于原来的问题“那么在转换指针时我应该得到 bad_cast 吗?”,不。
这就是为什么你可以看到类似的结构
关于新问题“这个 try-catch 块不合适吗?”,不,它是一个
try< /code>-
catch
块来捕获分配错误;它与dynamic_cast
本身无关。干杯&呵呵,
Regarding the original question "So should I get bad_cast when casting pointers?", No.
That's why you can see constructions like
Regarding the new question "Is this try-catch block inappropriate?", no, it is a
try
-catch
block to catch allocation errors; it's not related to thedynamic_cast
as such.Cheers & hth.,
由于
dynamic_cast
不会引发异常,因此完全不需要 try-catch 块之一。但是,您可以轻松定义自己的强制转换函数,该函数确实会引发指针异常。这就是我在自己的代码中所做的事情(简化的代码,请注意,我使用垃圾收集,这样我就可以抛出指针而不会产生任何后果):
顺便说一句,我也将它用作 static_cast 的语法糖,但这只是可能是因为我不使用它来dynamic_cast引用和const引用:
我想说你最好实现自己的转换函数,该函数在异常处理方面是一致的,并且精确地执行你想要和期望的操作。我做到了,并且再也没有回头。
Since
dynamic_cast<T*>
does not throw exceptions, one of the try-catch blocks are completely unnecessary.However you can easily define your own cast function that does indeed throw exception for pointers. That is what I am doing in my own code (simplified code, and mind you I use garbage collection so I can throw pointers without consequence):
On a side note, I also use it as a syntactic sugar for static_cast, but this is only possible because I do not use it to dynamic_cast references and const references:
I'd say you are better off implementing your own casting function that is coherent in terms of exception handling and do precisely what you want and expect. I did and never looked back.