I've never needed generic scope guards, but can
try something randomly:
#include <iostream>
#include <memory>
#include <string>
// some ugly macros to get unique_ptr useful
#define TP1(X, Y) X ## Y
#define TP2(X, Y) TP1(X, Y)
#define DEFER(CAPTURE,CODE) \
auto TP2(LMB,__LINE__) = [CAPTURE]() CODE; \
std::unique_ptr<decltype(TP2(LMB,__LINE__)), void(*) \
(decltype(TP2(LMB,__LINE__))*)> TP2(DEFERER,__LINE__) \
(&TP2(LMB,__LINE__), [](auto* p) {(*p)();})
// usage
int main ()
{
std::string str( "hello world" );
DEFER(&str,
{
std::cout << str << " 1" << std::endl;
});
std::cout << "doing some stuff\n";
DEFER(&str,
{
std::cout << str << " 2" << std::endl;
});
std::cout << "doing more stuff\n";
return 0;
}
output:
doing some stuff
doing more stuff
hello world 2
hello world 1
Perhaps these macros confuse it more than help.