checked_delete提升安全性

來源:互聯網
上載者:User

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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.