Re:Popular Myths about C++, Part 1
by wmt on Tuesday December 09, 2014 @02:39PM
(#8725129)
My biggest issue with most garbage collection implementations is the lack of RAII. While I love the ease of reading and writing Python or Lua, I'd love to be able to create a local object, like an open file or a database connection, and have it destructed immediately on return.
[ Parent
| on HN ]
I'm not sure about Lua, but for Python it sounds like you may be interested in the "with" statement.
You can do this in all modern GC languages.
Either with a using/try with resources/with construct, or by using closures.
// Pseudo language with FP capabilities
let withFile filename action =
let fd = open filename
action fd
close fd
withFile "config.sys" (fun fd -> write (readlines fd))
Real production code would also take care about proper closing the file in case of errors.