boost提供了一個安全的用於delete模板函數,在檔案checked_delete.hpp中:
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的指標,舉個例子:
class B;void Destroy(B* b) { delete b;}
如果你不調用這Destroy函數的話,G++不會報錯,但是會顯示警告:
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 definedmkdir -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會導致這一個編譯錯誤。
因此這是一個在編譯複雜的C++代碼時非常安全的好工具,只是編譯時間多花點時間。
同樣,還有一個很有用的工具用來安全的delete數組。
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;}