前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Code Review之delete后置空

Code Review之delete后置空

作者头像
用户5521279
发布2019-06-02 16:34:48
5770
发布2019-06-02 16:34:48
举报
文章被收录于专栏:搜狗测试搜狗测试搜狗测试
// 某个单例CxxxDemo* CxxxDemo::getInstance(){if (s_pInstance == nullptr){s_pInstance = new CxxxDemo();}return s_pInstance;}void CxxxDemo::destoryInstance(){delete s_pInstance;}// 使用demo = CxxxDemo::getInstance();// 省略中间代码.........CxxxDemo::destoryInstance();

大部分同学应该都发现了,单例的destoryInstance函数没有在delete之后将s_pInstance 置空。本次使用没问题,但下次getInstance就会返回一个野指针

问题分析

分析这个问题,实际上就是在delete之后没有置空,那么问题来了:

我们在做Code Review时是否要将delete后必须置空作为一条规则呢?

首先我们来看看如果delete后都统一置空,会怎样呢?

分以下两种情况:

  1. delete之后再次使用到该指针,这时如果置空了从程序的健壮性来说肯定是好的,就像上面的单例可以避免使用野指针的风险;
  2. delete之后再次delete该指针,我们查了下C++03标准: 5.3.5/7 If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will call a deallocation function (3.7.4.2). Otherwise, it is unspecified whether the deallocation function will be called. 3.7.4.2/3 The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. 所以置空后再次delete也是没有问题的(什么?为什么查C++03标准,都C++11/14了为什么不用智能指针)。

看起来在delete后置空是有百利而无一害的,那么问题又来了:

C++为什么不在delete后直接强行置空呢?

在C++ Standard的FAQ里我们找到这么一段回答:

Since deleting a null pointer is harmless by definition, a simple solution would be for delete p; to do a p=nullptr; after it has done whatever else is required. However, C++ doesn’t guarantee that. One reason is that the operand of delete need not be an lvalue.

理由很简单,delete后面跟随的不一定是左值。

所以我们在delete之后一定要手动置空吗?

在我们这份代码里,逻辑使然是必须的。但如果是一个常规的指针,我们的预期往往是delete之后就不会再被使用了,如果程序因为逻辑异常再次使用了该指针,你在delete之后置空虽然可以避免野指针相关的程序崩溃,但也会导致这个逻辑异常不易被暴露出来。

结论

综上所述,关于指针的delete问题我们有以下三点建议:

  1. 类似上面单例这种代码的,逻辑使然,必须置空;
  2. 常规指针的delete,明确之后不会再使用的,不建议置空;
  3. 情况允许,多使用智能指针。

后续我们会在每周二分享一些Code Review中遇到的问题,以及常用的方法和工具。大家对于Code Review有什么见解也欢迎一起交流讨论。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 搜狗测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题分析
  • 结论
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档