C++核心准则CP.20:使用RAII,永远不要直接使用lock/unlock
共 1319字,需浏览 3分钟
·
2020-07-01 23:21
CP.20: Use RAII, never plain lock()/unlock()
CP.20:使用RAII,永远不要直接使用lock/unlock
Reason(原因)
Avoids nasty errors from unreleased locks.
避免由于锁没有释放而引起的严重问题。
Example, bad(反面实例)
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.
早晚会有人忘记调用mtx.unlock(),将return语句放到...do stuff...的位置,抛出异常,或做点什么。
mutex mtx;
void do_stuff()
{
unique_lock lck {mtx};
// ... do stuff ...
}
Enforcement(实施建议)
Flag calls of member lock() and unlock(). ???
标记直接调用lock或unlock成员函数的代码。
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,是一种必须在使用之前必须执行获取动作的资源(堆内存,线程,socket,文件,mutex,内存空间,数据库链接-以优先供给方式提供的任何东西)的生命周期和某个对象的生命周期绑定的C++编程技术。
----https://en.cppreference.com/w/cpp/language/raii
原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp20-use-raii-never-plain-lockunlock
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!