C++ 学习笔记(14)RAII 资源管理型模板化

对比 C++ RAII 泛化,进一步把资源封装在 RAII 中,向外提供接口

尚不完善,仅作记录用

#include <bits/stdc++.h>
#define rep( i , j , n ) for ( int i = int(j) ; i < int(n) ; ++i )
#define dew( i , j , n ) for ( int i = int(n-1) ; i > int(j) ; --i )
#define _PATH __FILE__ , __LINE__
typedef std::pair < int , int > P ;
using std::cin ;
using std::cout ;
using std::endl ;
using std::string ;

namespace YHL {
    // RAII 负责“撤销”操作 和 管理资源 resource
    template<typename T>
    class RAII final {
        using funType = std::function<void(T &)> ;
    private:
        T resource ;  // 资源
        funType release ;   // 释放资源动作
        mutable bool dismissed ;  // 是否撤销的标志
    public:
        // 利用 acquire 得到资源
        explicit RAII(std::function<T()> acquire, funType _release)
            : resource(acquire())
            , release(_release)
            , dismissed(false)
        {}
        // 析构函数时实现 ScopeGuard
        ~RAII() noexcept {
            if ( dismissed == false )
                release(resource) ;
        }
        // 更改是否撤销
        void Dismiss(const bool _dismissed) noexcept {
            dismissed = _dismissed ;
        }
        // 转移资源所有权
        RAII(RAII &&other)
            : resource(std::move(other.resource))
            , release(std::move(other.release))
            , dismissed(other.dismissed) {
            // other 不执行回收资源的操作
            other.Dismiss(true) ;
        }
        // get() 得到资源
        T& get() {
            return resource ;
        }
        // * 操作符得到资源
        T& operator*() noexcept {
            return resource ;
        }
        // 禁止复制和赋值
        RAII(const RAII&) = delete ;
        RAII& operator=(const RAII&) = delete ;
        // 选择 -> 操作符模板
        template<typename _T = T>
        typename std::enable_if<std::is_pointer<_T>::value, _T>::type
	        operator->() const noexcept {
        	return resource ;
        }
        template<typename _T = T>
        typename std::enable_if<std::is_class<_T>::value, _T*>::type
	        operator->() const noexcept {
        	return std::addressof(resource) ;
        }
    } ;
}

int main () {
    YHL::RAII<int> someOne([]{
    	return int(10) ;
    }, [](int target){
    	cout << "目标已清理\n" ;
    }) ;
    auto target = someOne.get() ;
    cout << target << endl ;
    return 0 ;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值