Debian Codegraph @

examples/cxx/excxx_repquote/dbc_auto.h

raw
1 /*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2008, 2013 Oracle and/or its affiliates. All rights reserved.
5 *
6 * $Id$
7 */
8
9 #include <db_cxx.h>
10
11 /*
12 * Resource-acquisition-as-initialization pattern for Berkeley DB's cursors.
13 *
14 * Use DbcAuto instead of Berkeley DB's builtin Dbc class. The constructor
15 * allocates a new cursor, and it is freed automatically when it goes out of
16 * scope.
17 *
18 * Note that some care is required with the order in which Berkeley DB handles
19 * are closed. In particular, the cursor handle must be closed before any
20 * database or transaction handles the cursor references. In addition, the
21 * cursor close method can throw exceptions, which are masked by the destructor.
22 *
23 * For these reasons, you are strongly advised to call the DbcAuto::close
24 * method in the non-exceptional case. This class exists to ensure that
25 * cursors are closed if an exception occurs.
26 */
27 class DbcAuto {
28 public:
29 DbcAuto(Db *db, DbTxn *txn, u_int32_t flags) {
30 db->cursor(txn, &dbc_, flags);
31 }
32
33 ~DbcAuto() {
34 try {
35 close();
36 } catch(...) {
37 // Ignore it, another exception is pending
38 }
39 }
40
41 void close() {
42 if (dbc_) {
43 // Set the member to 0 before making the call in
44 // case an exception is thrown.
45 Dbc *tdbc = dbc_;
46 dbc_ = 0;
47 tdbc->close();
48 }
49 }
50
51 operator Dbc *() {
52 return dbc_;
53 }
54
55 operator Dbc **() {
56 return &dbc_;
57 }
58
59 Dbc *operator->() {
60 return dbc_;
61 }
62
63 private:
64 Dbc *dbc_;
65 };