lmdb-safe/lmdb-typed.cc

15 lines
305 B
C++
Raw Normal View History

#include "lmdb-typed.hh"
2018-12-16 20:28:49 +01:00
unsigned int MDBGetMaxID(MDBRWTransaction& txn, MDBDbi& dbi)
{
Hide MDB*Transaction behind a unique_ptr front This is to prevent the issue with Object Slicing. With the previous solution (where MDB*Transaction are normal objects), consider the following code: MDBRWTransaction txn = env.getRWTransaction(); //! Invalid: We explicitly break this move because it would be //! unsafe: // MDBROTransaction ro_txn(std::move(txn)); //! Valid, RW inherits from RO now, so we can bind an RO //! reference to an RW transaction. MDBROTransaction &ro_txn = txn; //! Dangerous!! MDBROTransaction ro_txn2(std::move(ro_txn)); The last move there breaks the semantics of the RW transaction which is bound to the reference ro_txn. It looses its RW cursors, which remain partly inside the txn instance. All kinds of weird and bad things can happen here. For instance, the ro_txn2 would go out of scope before the txn, calling the destructor MDBROTransaction destructor (which defaults to commit instead of abort!) and only freeing parts of the cursors. Only then the MDBRWTransaction destructor is called, which will free the cursors which belong to the RW transaction which has already been committed. The only safe way to prevent Object Slicing in this scenario I could come up with is to disallow moves of the objects altogether and instead use unique_ptr as front for them. This also removes an additional dynamic allocation per RW transaction (for the cursor vector), since the address of that vector is now constant over the lifetime of the transaction without indirection.
2019-10-26 11:42:38 +02:00
auto cursor = txn->getRWCursor(dbi);
MDBOutVal maxidval, maxcontent;
unsigned int maxid{0};
if(!cursor.get(maxidval, maxcontent, MDB_LAST)) {
maxid = maxidval.get<unsigned int>();
}
return maxid;
}