135
Examples of Persistent Containers
Since the main goal for the libpmemobj-cpp design is to focus modifications to volatile
programs on data structures and not on the code, the use of libpmemobj-cpp persistent
containers is almost the same as for their STL counterparts. Listing 8-11 shows a
persistent vector example to showcase this.
Listing 8-11. Allocating a vector transactionally using persistent containers
33
#include
34
#include
35
#include
36
#include
37
#include "libpmemobj++/vector.hpp"
38
39
using vector_type = pmem::obj::experimental::vector;
40
41
struct root {
42
pmem::obj::persistent_ptr vec_p;
43
};
44
...
63
64
/* creating pmem::obj::vector in transaction */
65
pmem::obj::transaction::run(pool, [&] {
66
root->vec_p = pmem::obj::make_persistent
(/* optional constructor arguments */);
67
});
68
69
vector_type &pvector = *(root->vec_p);
Listing 8-11 shows that a pmem::obj::vector must be created and allocated in
persistent memory using transaction to avoid an exception being thrown. The vector
type constructor may construct an object by internally opening another transaction.
In this case, an inner transaction will be flattened to an outer one. The interface and
semantics of pmem::obj::vector are similar to that of std::vector, as Listing 8-12
demonstrates.
Chapter 8 libpmemobj-Cpp: the adaptable language - C++ and persistent memory
Précédent

- 161/457

Suivant