Skip to content

Latest commit

 

History

History
104 lines (83 loc) · 1.31 KB

README.md

File metadata and controls

104 lines (83 loc) · 1.31 KB

ScopeGuard

資源釋放助手類,支持lambda、指針、數組指針及自定義函數。

指针

auto p = new int(0);
{
    ON_SCOPE_EXIT(ScopeGuard::Delete, p);
}
assert(p == nullptr);

數組指針

auto a = new int[10](0);
{
    ON_SCOPE_EXIT(ScopeGuard::DeleteArray, a);
}
assert(a == nullptr);

lambda

int n = 0;
{
    ON_SCOPE_EXIT([&n]()
        {
            n = 1;
        });
}
assert(n == 1);

函數指針

void set(int& n, int m)
{
    n = m;
}

int n = 0;
{
    ON_SCOPE_EXIT(set, n, 1);
}
assert(n == 1);

注意C++11之前传引用要使用boost::ref,即上面需改為:

ON_SCOPE_EXIT(set, boost::ref(n), 1);

不可變引用需用boost::cref,C++11後使用無需。

函數返回值

int add(int a, int b)
{
    return a + b;
}

int n = 0;
{
    ON_SCOPE_EXIT(std::ref(n), add, 1, 2);
}
assert(n == 3);

此處的std::refboost::ref不可缺,可用SCOPE_GUARD_REF宏來作兼容,同理還有SCOPE_GUARD_CREF

提前執行

int n = 0;
{
    ScopeGuard set1([&n]()
        {
            n = 1;
        });
    set1.reset();
    assert(n == 1);
}

取消

int n = 0;
{
    ScopeGuard set1([&n]()
        {
            n = 1;
        });
    set1.release();
}
assert(n == 0);