跳轉到內容

更多 C++ 習語/作用域保護

來自華夏公益教科書

作用域保護

[編輯 | 編輯原始碼]
  • 確保資源始終在遇到異常時釋放,但在正常返回時不釋放
  • 提供基本異常安全保證

也稱為

[編輯 | 編輯原始碼]

資源獲取即初始化 (RAII) 習語允許我們在建構函式中獲取資源,並在作用域成功結束或由於異常而結束時在解構函式中釋放它們。它將始終釋放資源。這不是很靈活。有時我們不想在沒有丟擲異常的情況下釋放資源,但如果丟擲異常,我們確實希望釋放它們。

解決方案和示例程式碼

[編輯 | 編輯原始碼]

使用條件檢查增強 資源獲取即初始化 (RAII) 習語的典型實現。

class ScopeGuard
{
public:
  ScopeGuard () 
   : engaged_ (true) 
  { /* Acquire resources here. */ }
  
  ~ScopeGuard ()  
  { 
    if (engaged_) 
     { /* Release resources here. */} 
  }
  void release () 
  { 
     engaged_ = false; 
     /* Resources will no longer be released */ 
  }
private:
  bool engaged_;
};
void some_init_function ()
{
  ScopeGuard guard;
  // ...... Something may throw here. If it does we release resources.
  guard.release (); // Resources will not be released in normal execution.
}

已知用途

[編輯 | 編輯原始碼]
  • boost::mutex::scoped_lock
  • boost::scoped_ptr
  • std::auto_ptr
  • ACE_Guard
  • ACE_Read_Guard
  • ACE_Write_Guard
  • ACE_Auto_Ptr
  • ACE_Auto_Array_Ptr
[編輯 | 編輯原始碼]

參考資料

[編輯 | 編輯原始碼]
華夏公益教科書