1

I need to create a structure in shared memory. This is an example of the classes:

struct A{
 std::string str1;
 int val;
}
struct B{
  A inner;
  std::string name;
}

I could not find an example of this in the web, but after some search i was able to see that i might need to implement some allocators, and that types like string should not be used as bare, So i created an allocator for strings that looks like this:

typedef allocator<char, ip::managed_shared_memory::segment_manager> char_alloc 
class String2: public ip::basic_string<char, std::char_traits<char>, char_alloc > { public:     
    String2(char_alloc& _all): ip::basic_string<char, std::char_traits<char>,  char_alloc >(_all) {;} };

But now i have some problems trying to understand how i can create an allocator that works like this for both classes.

Does anyone have an example of something similar to this?

Thanks in advance

jpereira
  • 251
  • 2
  • 11

3 Answers3

0

You should try using char rather than std::string.

struct A{
 char str1[64];
 int val;
};

struct B{
 A inner;
 char name[64];
};
Bumble
  • 21
  • 5
0

Placement new can perhaps help. Suppose you have a pointer to shared memory created by some unknown means:

void* some_shared_mem; // initialized somehow
B* shared_B = new (some_shared_mem) B; // call the B constructor.
share_B->A.val = 5;

BUT, you should not put anything into shared memory that allocates pointers. Even if you guarantee that those pointers refer back to the shared memory, you cannot be certain that every process sharing the memory sees the shared memory at the same address. some_shared_mem might be 0x10000 in on program and 0x20000 in some other program. So even if the shared pointer is allocated out of the shared memory (at say 0x10010), the program where the mapping is 0x20000 will see the point as 0x10010 which is not inside the shared memory from its point of view.

So you can do what you attempting only as long as there are no references or pointers in the various structures you map onto the shared memory.

jmucchiello
  • 18,754
  • 7
  • 41
  • 61
0

This answer comes a little late but, for future reference, the "Containers of containers" section from the Interprocess library has this exact use case.

rocarvaj
  • 546
  • 4
  • 19