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

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

    By making effective use of destructors. When an exception is thrown in a try block, any object created within it will be destroyed immediately (and hence its destructor called).

    This is different from Java where you have no idea when an object's finalizer will be called.

    UPDATE: Straight from the horse's mouth: Why doesn't C++ provide a "finally" construct?

    0 讨论(0)
  • 2021-02-05 19:59

    Not completetely offtopic.

    Boiler Plating DB Resource Cleanup in Java

    sarcasm mode: Isn't the Java idiom wonderful?

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题