, std::string , .
Interprocess string . , boost::container::basic_string<> .
.
, (ad nauseam), .
, , , , , .
Live On Coliru №
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/container/scoped_allocator.hpp>
#include <iostream>
#include <string>
namespace bip = boost::interprocess;
namespace Shared {
using Segment = bip::managed_shared_memory;
using Manager = Segment::segment_manager;
template <typename T> using Alloc
= boost::container::scoped_allocator_adaptor<bip::allocator<T, Manager> >;
using String = bip::basic_string<char, std::char_traits<char>, Alloc<char> >;
template <typename K, typename V, typename Cmp = std::less<K> > using Map
= bip::map<K, V, Cmp, Alloc<std::pair<K const, V> > >;
struct Order {
using allocator_type = Alloc<char>;
template <typename S, typename Alloc>
Order(int i, S const& s, Alloc alloc = {}) : i(i), s(s, alloc) {}
int i;
String s;
};
}
int main() {
try {
using namespace Shared;
Segment segment(bip::open_or_create, "095540a3-ceaa-4431-828d-df21d5e384ae", 65536);
auto& pmap = *segment.find_or_construct<Map<int, Order>>("MySHMMapName")(segment.get_segment_manager());
if (pmap.empty()) {
std::cout << "Inserting data\n";
auto insert = [&pmap](int i, auto&& s) {
using namespace std;
pmap.emplace(piecewise_construct, tie(i), tie(i, s));
};
insert(1, "one");
insert(2, "two");
insert(3, "three");
} else {
std::cout << "Existing data:\n";
for (auto& [k,v] : pmap) {
std::cout << k << " " << v.i << " " << v.s << "\n";
}
}
} catch (std::exception &e) {
std::cout << " error " << e.what() << std::endl;
bip::shared_memory_object::remove("095540a3-ceaa-4431-828d-df21d5e384ae");
}
}
, Map<int, Order>: , , Order.
1: Map<int, String>
Map<int, String> ( std::piecewise_construct):
Live On Coliru
auto& pmap = *segment.find_or_construct<Map<int, String>>("MySHMMapName")(segment.get_segment_manager());
if (pmap.empty()) {
std::cout << "Inserting data\n";
pmap.emplace(1, "one");
pmap.emplace(2, "two");
pmap.emplace(3, "three");
}
2: Multi Index
Multi-Index, Order :
Live On Coliru
namespace bmi = boost::multi_index;
using Table = bmi::multi_index_container<Order,
bmi::indexed_by<
bmi::ordered_unique< bmi::member<Order, int, &Order::i> >
>,
Alloc<Order>
>;
, Multi Index , :
if (pmap.empty()) {
std::cout << "Inserting data\n";
pmap.emplace(1, "one", pmap.get_allocator());
pmap.emplace(2, "two", pmap.get_allocator());
pmap.emplace(3, "three", pmap.get_allocator());
} else {
std::cout << "Existing data:\n";
for (Order const& o : pmap) {
std::cout << o.i << " " << o.s << "\n";
}
std::cout << "Finding element 2:" << pmap.find(2)->s << "\n";
}
Existing data:
1 one
2 two
3 three
Finding element 2:two
¹, Coliru. 1- .