更多 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
- 資源獲取即初始化 (RAII)