fork(4) download
  1. #include <iostream>
  2.  
  3. template<typename T>
  4. class Deleter
  5. {
  6. T x;
  7. public:
  8. inline Deleter( const T functor ): x(functor) { };
  9. inline ~Deleter() { x(); };
  10. };
  11.  
  12. template<typename T>
  13. inline Deleter<T> finally( const T x )
  14. {
  15. return Deleter<T>(x);
  16. };
  17.  
  18. #define FINALLY_IMPL(line, code) auto deleter##line = finally( [&]() { code; } );
  19. #define FINALLY(code) FINALLY_IMPL(__LINE__, code)
  20.  
  21. class Test
  22. {
  23. private:
  24. int code;
  25. public:
  26. Test(int c): code(c) { std::cout << "Test(" << code << ");\n"; };
  27. ~Test() { std::cout << "~Test(" << code << ");\n"; };
  28. void method() { std::cout << "method(" << code << ")\n"; };
  29. };
  30.  
  31. void func()
  32. {
  33. Test *x = nullptr;
  34. FINALLY(
  35. delete x;
  36. );
  37.  
  38. {
  39. Test *y = nullptr;
  40. FINALLY(
  41. delete y;
  42. );
  43. y = new Test(1);
  44. y->method();
  45. };
  46. x = new Test(2);
  47. x->method();
  48. };
  49.  
  50. int main(int argc, char *argv[])
  51. {
  52. func();
  53. std::cout << "ok\n";
  54. return 0;
  55. }
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
Test(1);
method(1)
~Test(1);
Test(2);
method(2)
~Test(2);
ok