Is there a favored idiom for mimicing Java's try/finally in C++?

前端 未结 15 813
无人及你
无人及你 2021-02-05 19:16

Been doing Java for number of years so haven\'t been tracking C++. Has finally clause been added to C++ exception handling in the language definition?<

15条回答
  •  滥情空心
    2021-02-05 19:54

    To avoid having to define a wrapper class for every releasable resource, you may be interested in ScopeGuard (http://www.ddj.com/cpp/184403758) which allows one to create "cleaners" on the fly.

    For example:

    FILE* fp = SomeExternalFunction();
    // Will automatically call fclose(fp) when going out of scope
    ScopeGuard file_guard = MakeGuard(fclose, fp);
    

提交回复
热议问题