Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

However your implementation based on std::function might allocate, which is then non-zero cost compared to normal exit statements. Better directly store the lambda inside the class, which requires that to be generic (Finally<LambdaType>). That can be hidden by using the class via a templated function which uses types interference:

    auto cleanup_socket = make_scope_guard([&]{ close_socket(s); });
Searching for scope_guard yields lots of alternative implementations.


make_* functions are no longer necessary in C++17 which adds "Class template argument deduction" [1]. You can now do

  std::pair p{"aaa", 123};
and

  Finally guard{[]{cleanup();}};
without specifying template arguments.

[1] https://en.cppreference.com/w/cpp/language/class_template_ar...


Thx, I wasn't aware about this feature yet!




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: