检查不完全类型:
举例如下
//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