C++核心準(zhǔn)則CP.20:使用RAII,永遠(yuǎn)不要直接使用lock/unlock

CP.20: Use RAII, never plain?lock()/unlock()
CP.20:使用RAII,永遠(yuǎn)不要直接使用lock/unlock
Reason(原因)
Avoids nasty errors from unreleased locks.
避免由于鎖沒有釋放而引起的嚴(yán)重問題。
Example, bad(反面實(shí)例)
mutex mtx;
void do_stuff()
{
mtx.lock();
// ... do stuff ...
mtx.unlock();
}
Sooner or later, someone will forget the?mtx.unlock(), place a?return?in the?... do stuff ..., throw an exception, or something.
早晚會(huì)有人忘記調(diào)用mtx.unlock(),將return語(yǔ)句放到...do stuff...的位置,拋出異常,或做點(diǎn)什么。
mutex mtx;
void do_stuff()
{
unique_lock lck {mtx};
// ... do stuff ...
} Enforcement(實(shí)施建議)
Flag calls of member?lock()?and?unlock(). ???
標(biāo)記直接調(diào)用lock或unlock成員函數(shù)的代碼。
RAII
Resource Acquisition Is Initialization?or RAII, is a C++ programming technique[1][2]?which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the?lifetime?of an object.
資源獲取即初始化或者叫RAII,是一種必須在使用之前必須執(zhí)行獲取動(dòng)作的資源(堆內(nèi)存,線程,socket,文件,mutex,內(nèi)存空間,數(shù)據(jù)庫(kù)鏈接-以優(yōu)先供給方式提供的任何東西)的生命周期和某個(gè)對(duì)象的生命周期綁定的C++編程技術(shù)。
----https://en.cppreference.com/w/cpp/language/raii
原文鏈接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp20-use-raii-never-plain-lockunlock
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
