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

前端 未结 15 802
无人及你
无人及你 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 20:00

    An Example of how difficult it is to use finally correctly.

    Open and closing two files.
    Where you want to guarantee that the file is closed correctly.
    Waiting for the GC is not an option as the files may be re-used.

    In C++

    void foo()
    {
        std::ifstream    data("plop");
        std::ofstream    output("plep");
    
        // DO STUFF
        // Files closed auto-magically
    }
    

    In a language with no destructors but has a finally clause.

    void foo()
    {
        File            data("plop");
        File            output("plep");
    
        try
        {
            // DO STUFF
        }
        finally
        {
            // Must guarantee that both files are closed.
            try {data.close();}  catch(Throwable e){/*Ignore*/}
            try {output.close();}catch(Throwable e){/*Ignore*/}
        }
    }
    

    This is a simple example and already the code is getting convoluted. Here we are only trying to marshal 2 simple resources. But as the number of resources that need to be managed increases and/or their complexity increases the use of a finally block becomes harder and harder to use correctly in the presence of exceptions.

    The use of finally moves responsibility for correct usage onto the user of an object. By using constructor/destructor mechanism provided by C++ you move the responsibility of correct usage to the designer/implementer of the class. This is inheritanly safer as the designer only needs to do it correctly once at the class level (rather than have different users try and do it correctly in different ways).

提交回复
热议问题