4 ms·
RAII, AC/DC, and the "with" statement
- mattculbreth 18y agoUpmodded for superb title, no Beating Around the Bush.
- jimbokun 18y agoIs 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 18y agoThis 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 18y agoIt's also a really common code security problem in most C++ code written until ~2005 (meaning: most C++ code).
- benhoyt 18y agoI'm curious about this -- can you explain how it's a security problem, and why that changed ~2005?
- tptacek 18y agoThink 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.
- tptacek 18y agoThis 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
- snprbob86 18y agoYou 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.