I found an example on this link
I knew C++ does not support finally block, so if any exception thrown during retrieving data (ex: in while block), then Connection, Statement, and Result objects can not be released.
So, I wonder how (or when) these objects released… Or there is another way writing the code to release them?
P/S: I spent much time in other language such as Java, C#, therefore maybe my thought goes wrong in something. Correct me if anything wrong.
C++ doesn’t have
finallyblocks because it doesn’t need them. It has something much, much better: destructors.A class type object can have a destructor, which will be called for an instance of that class type object when the instance ceases to exist. Local variables, which have what is called “automatic storage duration,” cease to exist at the end of the block in which they are declared.
Destructors therefore should be used to manage resources. Rather than writing a
deleteexpression at the end of a block to destroy a dynamically allocated object, you should use a smart pointer to manage the lifetime of the object. For example, consider the following lines from the example program to which you link:This could instead be written as:
(If you are using an older compiler or C++ Standard Library implementation and you don’t have or can’t use
std::unique_ptr, you can usestd::auto_ptrfor this specific use case.)Note that here the lifetime of the connection object is managed automatically: you don’t have to remember to destroy the object and you don’t have to worry about performing special cleanup if an exception is thrown. The
std::unique_ptrdestructor will ensure that the connection object is destroyed.This technique of using destructors to perform resource cleanup is called Resource Acquisition Is Initialization (RAII) and is the most important idiom to understand and to use consistently in C++. It’s hard to manage resources correctly yourself; it’s a whole lot easier when you let the
}do all the hard work for you.