使用C++11新特性来实现RAII进行资源管理

方法一:借助auto、decltype、unique_ptr、Lambda表达式构造

sqlite3 *db = NULL;
auto deleter = [](sqlite3 *pdb){sqlite3_close(pdb);}
int nRet = sqlite3_open16(L"F:\\my.db",&db);
std::unique_ptr<sqlite3,decltype(deleter)> pdb(db,deleter);

if(nRet)
{//失败,但是这里不用担心资源管理了
}
else
{
}
//其他操作
//结束前,会动释放资源

方法二:借助auto、decltype、bind/function、Lambda表达式构造

定义:

class ResourceGuard
{
private:
    std::function<void()> m_funcOnExit;
private:
    ResourceGuard(const ResourceGuard&);
    ResourceGuard &operator=(const ResourceGuard&);
public:
    explicit ResourceGuard(function<void()> _func):m_funcOnExit(_func)
    { }
    ~ResourceGuard()
    {
        m_funcOnExit();
    }

};
#define GUARD(callable) ResourceGuard guard__LINE__(callable)

使用:

    HANDLE hFile= ::CreateFileW(L"F:\\a.txt",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,NULL);

    GUARD ([&]() {if (hFile != INVALID_HANDLE_VALUE)
    {
        CloseHandle(hFile);
        hFile = INVALID_HANDLE_VALUE;}
    });

或:
    hFile = ::CreateFileW(L"F:\\a.txt",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,NULL);


    auto file_closer = [](HANDLE hFile){
        if(hFile != INVALID_HANDLE_VALUE)
        {
            cout<<"Open File Succeeded! Now Close it With Lambda expression!"<<endl;
            CloseHandle(hFile);
            hFile = INVALID_HANDLE_VALUE;
        }};
    std::unique_ptr<void,decltype(file_closer)> hFer(hFile,file_closer);


你可能感兴趣的:(C++)