A quick design question about C++ container classes in shared memory
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
it开发者_开发技巧self 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.
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.
精彩评论