[antlr-interest] "finally" blocks

Alan Gutierrez alan-antlr-interest at engrm.com
Mon Jan 17 21:49:29 PST 2005


* Paul J. Lucas <pauljlucas at mac.com> [2005-01-17 18:38]:
> On Mon, 17 Jan 2005, Terence Parr wrote:
> 
> > Interesting...was wondering how to do that in C++.  I wonder if it's 
> > general though.
> 
> 	It's trivial to make a templated "flag" class that takes any
> 	type T.
> 
> > A finally clause can play with all sorts of local variables and call methods
> > etc...
> 
> 	I don't have Bjarne's book in front of me, but he talks about
> 	the general concept is about resource aquisition and release
> 	(which is mostly what "finally" in Java is used for, e.g., open
> 	a file, make sure it's closed, etc.).

    RAII. Resource Allocation is Initialization. Modern C++ relies
    heavily on the use of destructors to restore state when the
    stack is unwound. The question as to whether it is general, I'm
    not sure I understand. If you're wondering whether it is a
    generally accepted practice in C++, the answer is yes.

> 	In practice, "finally" code generally only needs to reset a
> 	small number of things, so it's not as bad as you might think.
> 
> > Would ANTLR need to analyze C++ actions (shudder) in order to construct the
> > bool_flag(arglist) thing?  Probably.

    No. It simply falls out of proper C++ use.

    int foo()
    {
        std::vector<int> nums(10);      // Create a vector of nums
                                        // possibly allocating heap
                                        // memory.

        do_something_that_might_throw(nums); 

        // ~std::vector<int>() frees the memory no matter what.
    }


> 	In ANTLR for C++, you don't need "finally" at all because if
> 	the user wants the functionality, s/he can simply do what I
> 	did, i.e., create a variable having a destructor.

    And a decent C++ type is built around RAII and a destrcutor that
    does the right thing.

> 	The only reason I want "finally" in ANTLR is because I'm using
> 	Java (only because I'm paid to) and Java needs "finally".

> 	But this implies that ANTLR for Java and ANTLR for C++ would be
> 	different.

    You could still have that finally block for C++, no problem, but
    C++ programmers wouldn't find much use for it. Finally exists in
    C++, but the state of the art is such that it is not the best form.

    Finally strikes me as a universal concept in any langauge that
    has exceptions, Python, C++, Perl 5/6, Java, C# all have it.
    
    A C target is a challenge.

--
Alan Gutierrez - alan at engrm.com


More information about the antlr-interest mailing list