|
Boost : |
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2024-12-20 18:22:29
On 12/20/24 20:15, Murali Kishore via Boost wrote:
> Hi,
>
> Want to check is std::variant allocating memory from shared memory using
> boost interprocess allocators.
>
> EX: std::variant<int, float> v, w;
>
> // Define types A and B that we will store in the variant
> struct A {
> int x;
> A(int val) : x(val) {}
> };
>
> struct B {
> std::string str;
> B(const std::string& s) : str(s) {}
> };
>
> // Define the variant type
> using MyVariant = std::variant<A, B>;
>
> guide me for the above examples to create custom allocators.
std::variant itself does not perform dynamic memory allocations, so
there's nothing to be done with it.
Other types, like std::string and containers, do perform allocations and
must be customized with Boost.Interprocess allocators. See here:
The allocators operate on a shared memory segment internally, which must
be allocated or opened beforehand. The segment can also be used
directly, for example, to allocate objects in the shared memory. See here:
https://www.boost.org/doc/libs/1_87_0/doc/html/interprocess/managed_memory_segments.html
However, not all standard libraries have good support for stateful
allocators (or at least not all of them did at some point), so it is
better to replace std strings and containers with the equivalents from
Boost.Container. For example:
namespace ipc = boost::interprocess;
using ipc_char_allocator = ipc::allocator<char,
ipc::managed_shared_memory::segment_manager>;
using ipc_string = boost::container::basic_string<
char, std::char_traits<char>, ipc_char_allocator>;
struct B {
ipc_string str;
B(const std::string_view& s,
managed_shared_memory::segment_manager* mgr) :
str(s, ipc_char_allocator(mgr))
{}
};
// Create shared memory
ipc::managed_shared_memory segment(ipc::create_only,
"MyName", 65536);
// Construct a named instance of B in the shared memory
B* b = segment.construct< B >("MyBInstance")
("hello", segment.get_segment_manager());
// Destroy the instance of B
segment.destroy_ptr(b);
Disclaimer: The above code is untested.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk