views:

148

answers:

1

I am writing a simple wrapper around boost::interprocess's vector container to implement a ring buffer in shared memory (shm) for IPC. Assume that buf is an instance of RingBuffer created in shm. Now, in its ctor, buf itself allocates a private boost::interprocess::vector data member to store values, e.g. m_data. My question is: I think m_data should also be created in shared memory. But it this a necessity?

What happens if buf that was created in shm itself, allocates standard memory, i.e. using new. Does this get allocated on the calling process's heap? I don't think buf is allocated there so how come a data member that is private to an object not on a process's heap gets allocated there. I'm confused.

+2  A: 

boost::interprocess::vector takes an allocator type as a template parameter. This allocator needs to allocate from the shared memory (see the examples of use).

If you class allocates memory with new, then that memory will only be accessible from the process it was allocated in. This is wrong, and is exactly why boost::interprocess::vector needs a shared memory allocator.

in its ctor, buf itself allocates a private boost::interprocess::vector data member

This doesn't make sense to me. In C++, you cannot "allocate" a data member in a constructor. Data members are defined in the class body, and they are part of each object of that class. They're in the same memory the object is, for the same reason that the middle byte of a 4-byte integer is in the same memory that the integer is.

how come a data member that is private to an object not on a process's heap gets allocated there

Memory is allocated how you ask for it to be allocated. If you allocate with new (and it hasn't been overloaded), then it's allocated in process memory. If you allocate with a shared memory segment manager (which is what I think Boost calls it - I haven't actually used those APIs myself), it's allocated in shared memory. The class which contains the call, and the data member where you store the pointer to the allocated memory, have nothing to do with it.

Steve Jessop
Thanks Steve, that clears up a lot of my confusion. My remaining question is: Should the `buf` class created in shm use `boost::interprocess::vector` or `std::vector` to store its data? I think it's got to be the boost version, just wanted to know if that's correct.
recipriversexclusion
Yes, it has to be the interprocess. `std::vector` allocates memory and stores pointers to it. By default it allocates using `new`, which would be wrong as we know. But even if you give `std::vector` an allocator which allocates from shared memory, it would *still* be wrong, because the shared memory might not be mapped to the same address range in all processes, and if it isn't then the pointers won't work. `boost::interprocess::vector` deals with that for you.
Steve Jessop