

RAII, AC/DC, and the "with" statement - benhoyt
http://blog.brush.co.nz/2009/02/raii-acdc/

======
snprbob86
You need to be careful when allocation multiple resources in a constructor. If
the second initialization operation fails, the
deconstructor/finalizer/disposer/whatever is not called. This means that the
first object will never be cleaned up.

In general, it is wise to allocate only one unmanaged (non-garbage collected)
resource per constructor.

------
tptacek
This is a natural idiom in Ruby as well, built into most of the standard
library classes; resource classes accept blocks for their initializers that
invoke "close" when the block completes.

    
    
       File.open("foo.txt", "w") do |f|
          f.write("this is a test\n")
       end

------
jimbokun
Is there a way to do RAII in Java?

First couple of hits for "Java RAII" on Google suggest "no," but I think the
HN audience might be smarter than Google about this. I just recently
introduced (then found and fixed) a bug where I forgot to release a resource,
and if there is an idiom that doesn't make me manually match every resource
allocation with its inverse, I'd like to know about it. Looks like Java might
be last to the "automated freeing of non-memory resources" party.

------
makecheck
This is a very useful thing, and it's crucial that programmers learn it.

And though it doesn't specifically say so in the article, this technique
really needs to be applied _everywhere_ in a C++ program and its libraries.
Maybe your program doesn't throw exceptions, but something else might; if your
cleanup isn't automatic, it may not always occur.

~~~
tptacek
It's also a really common code security problem in most C++ code written until
~2005 (meaning: most C++ code).

~~~
benhoyt
I'm curious about this -- can you explain how it's a security problem, and why
that changed ~2005?

~~~
tptacek
Think of code executing say 30 stack frames in, generating an exception not
caught until all the way up to 5 frames in (a very common situation). That
exception cuts a swath through 25 functions, leaving stale variables and
dangling pointers.

~~~
litewulf
RAII is pretty old isn't it? What changed in 2005?

~~~
tptacek
RAII is 1995. I don't know what changed in 2005.

~~~
kragen
Maybe all the people who were writing in C++ without using RAII switched to
writing Java by then.

------
mattculbreth
Upmodded for superb title, no Beating Around the Bush.

