当来自“新”的指针出现时,如何跟踪情况?表达式传递给dynamic_cast?
最近我在查看一些旧代码时发现了以下内容:
auto_ptr<DerivedClass> pointer = dynamic_cast<CBase*>( new CDerived() );
除了这个代码在有效情况下毫无意义之外(在有效情况下class Derived
是从class Base
派生的,并且没有dynamic_cast
是必要的)对象所有权存在问题。如果出于某种原因 dynamic_cast
返回空指针,则 auto_ptr
将不会绑定到创建的对象,并且该对象将被泄漏。
是否有一些技术可以帮助防止此类错误,例如使编译器发出警告或类似的内容?
Recently I found the following while reviewing some old code:
auto_ptr<DerivedClass> pointer = dynamic_cast<CBase*>( new CDerived() );
aside from the fact that this code is meaningless in valid cases (in valid cases class Derived
is derived from class Base
and no dynamic_cast
is necessary) there's a problem with object ownership. If for whatever reason dynamic_cast
returns a null pointer the auto_ptr
will not be bound to the created object and the object will be leaked.
Is there some technique to help prevent such errors like making a compiler issue a warning or anything like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
摆脱所有
dynamic_cast
。所有的人。
那么就不需要跟踪了。
Get rid of all your
dynamic_cast
s.All of them.
Then no tracking will be necessary.
如果您找不到任何可用的内容,您还可以添加自己的 规则到cpp 检查
If you can't find anything already available you can also add your own rule to cpp check