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

前端 未结 15 776
无人及你
无人及你 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:53

    No finally has not been added to C++, nor is it likely to ever be added.

    The way C++ uses constructor/destructor makes the need for finally unnecessary.
    If you are using catch(...) to cleanup then you are not using C++ properly. The cleanup code should all be in the destructor.

    Though it is not a requirement to use it C++ does have a std::exception.
    Forcing developers to derive from a specific class to use exception goes against the keep it simple philosophy of C++. Its also why we don't require all classes to derive from Object.

    Read: Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

    The use of finally is more error prone than destructors to do clean up.
    This is because you are forcing the user of the object to do clean up rather than the designer/implementer of the class.

提交回复
热议问题