您的位置:首页 > 其它

WTF之安全删除对象

2012-12-19 21:27 134 查看
在 source/javascriptcore/wtf/OwnPtrCommon.h中有这么一段代码:

template <typename T> inline void deleteOwnedPtr(T* ptr)

{
    typedef char known[sizeof(T) ? 1 : -1];

    if (sizeof(known))

      delete ptr; 

}

该函数让编译器检查不完整类型(incomplete types),以实现安全删除对象,boost中也有类
4000
似的技法:

//http://www.boost.org/doc/libs/1_35_0/boost/checked_delete.hpp

// verify that types are complete for increased safety

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;

}

这里利用了sizeof操作符应用到不完整类型上面时,编译器会报错;即使在某些编译器上通过了编译,声明一个大小为-1的数组,也会报错。

--------------------------------------------------------------------------------------

不完整类型,包括:

1. void

2. 未知大小的数组

3. 不完整类型元素的数组

4. 没有定义的结构、联合,或者枚举

5. 声明但没有定义的类

6. 指向声明但没有定义类的指针 

sizeof操作符不能用在以下操作数上:

(摘录于:http://msdn.microsoft.com/en-us/library/4s7x1k91(v=vs.71).aspx

1.Functions (However, sizeof can be applied to pointers to functions)

2.Bit fields

3.Undefined classes

4.The type void

5.Dynamically allocated arrays

6.External arrays

7.Incomplete types

8.Parenthesized names of incomplete types
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  delete 删除 安全