Your understanding is correct. Sample
Acquire some resource Do something Release resource
is fundamentally wrong, because Do something can potentially cause an exception and a resource leak. In addition, you must remember to free up a resource, which is a fertile source of error.
The correct way, as you indicate, is to always use an object whose destructor frees the resource. This is called the RAII name in C ++.
This means, for example. never using delete external destructors or never relying on manual closing of file descriptors, never unlock mutexes manually, etc. Learn about smart pointers and use them whenever you can.
Note that some languages โโ(not C ++) provide a finally keyword that allows you to execute a block of instructions regardless of whether an exception is thrown. C ++ uses RAII, and you should never care about releasing a resource if you write the correct destructors.
I have a small utility there for C ++ 0x, which allows you to execute arbitrary code on block exit if you interact with poorly written (or C) libraries once or twice.
source share