当前位置:编程学习 > 网站相关 >>

checked_delete提升安全性

boost提供了一个安全的用于delete模板函数,在文件checked_delete.hpp中:

[cpp] 
template<class T> inline void checked_delete(T * x) 

    // intentionally complex - simplification causes regressions 
    typedef char type_must_be_complete[ sizeof(T)? 1: -1 ]; 
    (void) sizeof(type_must_be_complete); 
    delete x; 

为什么? 因为对一个incomplete type的指针运行delete操作结果是未定义的。
什么时候会出现incomplete type的指针,举个例子:

[cpp] 
class B; 
 
void Destroy(B* b) { 
    delete b; 

如果你不调用这Destroy函数的话,G++不会报错,但是会显示警告:
[cpp]
main.cpp:30:12: warning: possible problem detected in invocation of delete operator: [enabled by default] 
main.cpp:29:6: warning: ‘b’ has incomplete type [enabled by default] 
main.cpp:27:7: warning: forward declaration of ‘class B’ [enabled by default] 
main.cpp:30:12: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined 
mkdir -p build/Debug/GNU-Linux-x86 
B就是一个incomplete type.
这是个警告,但不是错误,为什么?因为C++标准是允许的,只说结果未定义,各个编译器自己决定吧。


5.3.5/5:

"If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined."

现在boost用typedef来进行编译期检查。这种typedef ....  在我前面分析boost::bind代码的时候曾经见过。数组不允许长度为-1,而incomplete type会导致这一个编译错误。www.zzzyk.com
因此这是一个在编译复杂的C++代码时非常安全的好工具,只是编译时多花点时间。

 

同样,还有一个很有用的工具用来安全的delete数组。

[cpp] 
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; 

 

补充:综合编程 , 安全编程 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,