LINUX.ORG.RU

История изменений

Исправление wota, (текущая версия) :

можно точно так же написать функцию:

#include <iostream>
using namespace std;

template<typename T, typename U> inline
void unwind_protect( T protect, U cleanup )
{
    try
    {
        protect();
    }
    catch(...)
    {
        cleanup();
        throw;
    }

    cleanup();
}

int main() {
    unwind_protect(
        []() { throw 1; },
        []() { cout << "cleanup\n"; } );
}

если хочешь можешь макросы добавить:

#define protect(...) unwind_protect( [&]() { __VA_ARGS__; }
#define cleanup(...) , [&]() { __VA_ARGS__; } );

int main() {
    protect(
        cout << "test\n";
        throw 1;
    )
    cleanup(
        cout << "cleanup\n"
    )
}

Исходная версия wota, :

можно точно так же написать функцию:

~$ cat 1.cpp
#include <iostream>
using namespace std;

template<typename T, typename U> inline
void unwind_protect( T protect, U cleanup )
{
    try
    {
        protect();
    }
    catch(...)
    {
        cleanup();
        throw;
    }

    cleanup();
}

int main() {
    unwind_protect(
        []() { throw 1; },
        []() { cout << "cleanup\n"; } );
}

~$ g++ -std=c++11 1.cpp
~$ ./a.out 
cleanup
terminate called after throwing an instance of 'int'

если хочешь можешь макросы добавить:

#define protect(...) unwind_protect( [&]() { __VA_ARGS__; }
#define cleanup(...) , [&]() { __VA_ARGS__; } );

int main() {
    protect(
        cout << "test\n";
        throw 1;
    )
    cleanup(
        cout << "cleanup\n"
    )
}