The Guard Class with Templates
If your compiler supports templates, you can use the guard class to guarantee that the acquire() and release() functions are called in pairs. The guard class is not provided by the DB Interface Module; it must be supplied by your application. Here is how it looks:
 
template<class T>
class Guard {
T& object_;
public:
Guard(const T& t)
: object_((T&)t) { object_.acquire(); }
~Guard()
{ object_.release(); }
};
The guard class expects type T to provide the acquire() and release() functions. If type T provides them, the functions are called in the constructor and destructor, respectively; if type T does not, the compiler should flag an error. Nearly all classes of the DB Interface Module provide the necessary interface used by the guard class. The guard class can be applied as follows:
Example 19 – Using a guard class with templates
 
void doSomething(const RWDBConnection& conn) {
// We’re going to use the connection so we’d better
// control access.
Guard<RWDBConnection> guard(conn); // RWDBConnection supports the
// necessary interface.
// Do something on the Connection.
 
// The mutex is released when the Guard instance goes out of
// scope.
}