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 ;
}

猜你喜欢

转载自blog.csdn.net/nishisiyuetian/article/details/81623453
今日推荐