136
Listing 8-12. Using persistent containers
71
pvector.reserve(10);
72
assert(pvector.size() == 0);
73
assert(pvector.capacity() == 10);
74
75
pvector = {0, 1, 2, 3, 4};
76
assert(pvector.size() == 5);
77
assert(pvector.capacity() == 10);
78
79
pvector.shrink_to_fit();
80
assert(pvector.size() == 5);
81
assert(pvector.capacity() == 5);
82
83
for (unsigned i = 0; i < pvector.size(); ++i)
84
assert(pvector.const_at(i) == static_cast(i));
85
86
pvector.push_back(5);
87
assert(pvector.const_at(5) == 5);
88
assert(pvector.size() == 6);
89
90
pvector.emplace(pvector.cbegin(), pvector.back());
91
assert(pvector.const_at(0) == 5);
92
for (unsigned i = 1; i < pvector.size(); ++i)
93
assert(pvector.const_at(i) == static_cast(i - 1));
Every method that modifies persistent memory containers does so inside an implicit
transaction to guarantee full exception safety. If any of these methods are called inside
the scope of another transaction, the operation is performed in the context of that
transaction; otherwise, it is atomic in its own scope.
Iterating over pmem::obj::vector works exactly the same as std::vector. We can
use the range-based indexing operator for loops or iterators. The pmem::obj::vector
can also be processed using std::algorithms, as shown in Listing 8-13.
Chapter 8 libpmemobj-Cpp: the adaptable language - C++ and persistent memory
Précédent

- 162/457

Suivant