是否可以在私有内存 space 中分配一个用于提升托管共享内存的对象?

Is it possible to allocate in private memory space an object made for boost managed shared memory?

假设我输入了一个要在提升共享内存中使用的向量。创建它时,我必须从 managed_shared_memory 中给出一个分配器,这是有道理的。

如果我想使用相同的向量类型但不是在共享内存中分配它而是在标准进程内存中分配它space。

是否可以通过为对象提供不同的分配器来实现?

我是否必须更改向量的定义才能接受这两种实现?

这是不可能的,因此我应该使用不同类型的向量吗?

我正在尝试修复的示例代码:

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>

using namespace boost::interprocess;

typedef managed_shared_memory::segment_manager SegmentMgr;
typedef allocator<int, SegmentMgr> IntAlloc;
typedef vector<int, IntAlloc> IntVector;

int main()
{
  shared_memory_object::remove("Boost");
  managed_shared_memory managed_shm{ open_or_create, "Boost", 1024 };
  IntAlloc intAlloc = managed_shm.get_segment_manager();
  IntVector vectorInSharedMemory({}, intAlloc);  // <--- this allocates in shared memory
  IntVector vectorInMyOwnPrivateMemorySpace({}, /* ? */); // <--- is there a trick here ?
  return 0;
}

是的。我之前已经对此进行了扩展回答:

  • boost::interprocess Containers of containers NOT in shared memory and the followup
  • making non-shared copies of boost::interprocess shared memory objects

What you call "private memory" is "the local heap" though. You can also have mapped memory with MAP_PRIVATE, which means something else (see mmap and e.g. Opening managed shared memory and mapped files with Copy On Write or Read Only modes)

I want to use this same vector type but to allocate it not in shared memory

让我们就此打住。它不再是同一个向量。由于分配器是vector的模板参数,不同的分配器代表不同的类型。

就像说 std::vector<int> 和 std::vector<double> 甚至不是同一类型一样简单。

Do I have to change the definition of my vector to be able to accept both implementations ?

是的,您可以使用别名声明来指定 IntVector 是参数化分配器的 int 向量。

template<typename Alloc> using IntVector=vector<int, Alloc>; // template definition

//    [...]

IntVector<IntAlloc> sharedMemoryVector;
IntVector<std::allocator<int>> localHeapVector;

您需要创建一个分配器 class,它可以在运行时切换为使用任一分配器。例如。像这样的东西(不是一个完整的例子,只是给你一个想法):

template < typename T >
class switchable_allocator
{
   boost::interprocess::allocator< T, SegmentMgr >* sharedAllocator;
   std::allocator< T > privateAllocator;

public:
   switchable_allocator(boost::interprocess::allocator< T, SegmentMgr >* sharedAllocator) : sharedAllocator(sharedAllocator) {}

   pointer allocate(size_t n)
   {
     if (sharedAllocator)
     {
       return sharedAllocator->allocate(n);
     }
     return privateAllocator.allocate(n);
   }
};