Hacker News new | ask | show | jobs
by applecore 4652 days ago
Java 7 introduced a new language construct, called the try-with-resources statement, for automatic resource management:

    void foo() {
        try (open file or resource here) {
            // do stuff
        }
        // after try block, resource will close automatically
    }
This works with non-memory resources such as files, streams, sockets, and database connections.
1 comments

Pasting a response:

Blocks are an improvement, but not the same as RAII. A block is literally converted to a try-finally by the compiler. It is the same thing with a cleaner syntax. There is no safety added to the old Java way. A programmer can forget to put his stuff in a block and leak the resource the same as he forgets to use a try-finally. The onus is on the consumer, not the library writer.

With C++ RAII the onus is removed from the consumer. The consumer writes safe code automatically, no onus to remember any special clean up idioms.

As long as the object is stack allocated or a member variable.
Well you do have to ban raw pointers. Heap allocation is safe with smart pointers.