fork(1) download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. template<typename F>
  5. [[nodiscard]] auto im_finally(F f, bool active = true) noexcept(noexcept(F(std::move(f)))) {
  6. auto x = [f = std::move(f)](void*){ f(); };
  7. return std::unique_ptr<void, decltype(x)>((void*)(active), std::move(x));
  8. }
  9.  
  10. inline [[nodiscard]] auto im_test_true() {
  11. return im_finally([]{ std::cout << "true ~dtor" << std::endl; }, true);
  12. }
  13.  
  14. inline [[nodiscard]] auto im_test_false() {
  15. return im_finally([]{ std::cout << "false ~dtor" << std::endl; }, false);
  16. }
  17.  
  18. int main() {
  19. if (auto false_guard = im_test_false())
  20. std::cout << "false operator bool()" << std::endl;
  21.  
  22. if (auto true_guard = im_test_true())
  23. std::cout << "true operator bool()" << std::endl;
  24.  
  25. return 0;
  26. }
Success #stdin #stdout 0s 15232KB
stdin
Standard input is empty
stdout
true operator bool()
true ~dtor