171
49
// Create std::vector with our allocator.
50
std::vector
51
libmemkind::pmem::allocator> v(alc);
52
53
for (int i = 0; i < 100; ++i)
54
v.push_back(i);
55
56
for (int i = 0; i < 100; ++i)
57
assert(v[i] == i);
• Line 43: We define a persistent memory pool of 64MiB.
• Lines 46-47: We create an allocator object alc of type
pmem::allocator.
• Line 50: We create a vector object v of type std::vector
pmem::allocator > and pass in the alc from line 47 object as
an argument. The pmem::allocator is stateful and has no default
constructor. This requires passing the allocator object to the vector
constructor; otherwise, a compilation error occurs if the default
constructor of std::vector > is called
because the vector constructor will try to call the default constructor
of pmem::allocator, which does not exist yet.
Creating a Vector of Strings
Listing 10-11 shows how to create a vector of strings that resides in persistent memory.
We define pmem_string as a typedef of std::basic_string with pmem::allocator.
In this example, std::scoped_allocator_adaptor allows the vector to propagate the
pmem::allocator instance to all pmem_string objects stored in the vector object.
Listing 10-11. vector_of_strings.cpp: creating a vector of strings
37 #include
38 #include
39 #include
40 #include
41 #include
Chapter 10 Volatile Use of persistent MeMory
49
// Create std::vector with our allocator.
50
std::vector
libmemkind::pmem::allocator
52
53
for (int i = 0; i < 100; ++i)
54
v.push_back(i);
55
56
for (int i = 0; i < 100; ++i)
57
assert(v[i] == i);
• Line 43: We define a persistent memory pool of 64MiB.
• Lines 46-47: We create an allocator object alc of type
pmem::allocator
• Line 50: We create a vector object v of type std::vector
an argument. The pmem::allocator is stateful and has no default
constructor. This requires passing the allocator object to the vector
constructor; otherwise, a compilation error occurs if the default
constructor of std::vector
because the vector constructor will try to call the default constructor
of pmem::allocator, which does not exist yet.
Creating a Vector of Strings
Listing 10-11 shows how to create a vector of strings that resides in persistent memory.
We define pmem_string as a typedef of std::basic_string with pmem::allocator.
In this example, std::scoped_allocator_adaptor allows the vector to propagate the
pmem::allocator instance to all pmem_string objects stored in the vector object.
Listing 10-11. vector_of_strings.cpp: creating a vector of strings
37 #include
38 #include
39 #include
40 #include
41 #include
Chapter 10 Volatile Use of persistent MeMory
