c++不完全类型检测

检查不完全类型:

举例如下

//BB.h

#include <iostream>
  2 class BB
  3 {
  4 public:
  5     BB()
  6     {
  7         std::cout<<"BB"<<std::endl;
  8     }
  9     ~BB()
 10     {
 11         std::cout<<"~BB"<<std::endl;
 12     }
 13 };

//AA.cpp
  1 #include <iostream>
  1 #include <iostream>
  2 class BB;
  3 class AA
  4 {
  5     public:
  6         void deleteBB(BB* pb)
  7         {
  8             delete pb;
  9         }
 10 
 11 };
 12 
 13 
 14 int main()
 15 {
 16     AA a;
 17     //a.deleteBB(new BB);
 18     return 0;
 19 }
当我们在AA.cpp中只声明了class BB,并没有对其定义,这时如果不调用deleteBB()编译器是不对其报错的,只是warning

AA.cpp: In member function ‘void AA::deleteBB(BB*)’:
AA.cpp:8:11: warning: possible problem detected in invocation of delete operator: [-Wdelete-incomplete]
    delete pb;
           ^
AA.cpp:6:21: warning: ‘pb’ has incomplete type
   void deleteBB(BB* pb)
                     ^
AA.cpp:2:7: note: forward declaration of ‘class BB’
 class BB;
       ^
AA.cpp:8:11: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined
    delete pb;

我们应该尽量让错误在编译时出现,而不是在执行时,所用可以使用一下方法

void deleteBB(BB* pb)
  7         {
  8             typedef char type_must_be_complete[sizeof(BB) ? 0:-1];
  9             (void) sizeof(type_must_be_complete);
 10             delete pb;
 11         }
如果BB是不完全类型那么sizeof(BB)就应该是0,type_must_be_complete[-1],数组是不能为负数的,所以就会报错
也可以使用boost的checked_array_delete(T * x);在头文件checked_delete.hpp中;

源码:

template<class T> inline void checked_array_delete(T * x)
{
    typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
    (void) sizeof(type_must_be_complete);
    delete [] x;

————————————————
版权声明:本文为CSDN博主「lhh1113」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lhh1113/java/article/details/56244194

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值