C++ RAII Resource Acquisition Is Initialization

RAII(Resource Acquisition Is Initialization)是C++中的一种编程范式,通过对象的生命周期来管理资源,确保资源在不再需要时会被正确释放。例如,在给出的例子中,`std::lock_guard`在构造时锁定mutex并在析构时解锁,从而避免了忘记解锁导致的潜在问题。RAII可以有效地防止资源泄露,提高代码的可靠性和安全性。
摘要由CSDN通过智能技术生成

RAII - cppreference.comhttps://en.cppreference.com/w/cpp/language/raii

​​​​​​std::mutex m;
 
void bad() 
{
    m.lock();                    // acquire the mutex
    f();                         // if f() throws an exception, the mutex is never released
    if(!everything_ok()) return; // early return, the mutex is never released
    m.unlock();                  // if bad() reaches this statement, the mutex is released
}
 
void good()
{
    std::lock_guard<std::mutex> lk(m); // RAII class: mutex acquisition is initialization
    f();                               // if f() throws an exception, the mutex is released
    if(!everything_ok()) return;       // early return, the mutex is released
}                 

        lock_guard构造时lock mutex ,析构时unlock mutex。bad中m忘了unlock。使用RAII可以避免出现这种错误。

如何评价 RAII 特性在 C++ 中的大范围运用? - 知乎类似的行为(靠对象的作用域/生存期来管理资源)在很多语言中也都存在,如 Python 的 context manager。…https://www.zhihu.com/question/37900510?sort=created

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值