在boost::interprocess
文档据说作为容器要求被存储在共享存储器:std :: vector是否满足Boost.Interprocess分配器的容器需求?
- STL容器可以不承担与分配器分配该存储器可以与相同类型的其他分配器被释放。所有分配器对象只有在分配一个对象的内存可以与另一个对象分配时才必须相等,并且这只能在运行时通过
operator==()
进行测试。 - 容器的内部指针应该是
allocator::pointer
的类型,并且容器可能不承担allocator::pointer
是一个原始指针。 - 所有物体必须通过
allocator::construct
和allocator::destroy
函数构造销毁。
我正在使用gcc 4.7.1和-std = C++ 11(和boost 1.53)。 使用以下定义的ShmVector
类型安全吗?
typedef boost::interprocess::allocator<int,
boost::interprocess::managed_shared_memory::segment_manager> ShmemAllocator;
typedef std::vector<int, ShmemAllocator> ShmVector;
我尝试使用这种类型的虚拟过程,它看起来它是工作,但我现在还不能确定,在gcc4.7.1矢量并满足所有的要求。我特别不确定第一个要求。
#include <iostream>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <vector>
#include <cstdlib> //std::system
typedef boost::interprocess::allocator<int,
boost::interprocess::managed_shared_memory::segment_manager> ShmemAllocator;
typedef std::vector<int, ShmemAllocator> ShmVector;
int main(int argc, char *argv[])
{
if(argc == 1){ //Parent process
struct shm_remove
{
shm_remove() { boost::interprocess::shared_memory_object::remove("MySharedMemory"); }
~shm_remove(){ boost::interprocess::shared_memory_object::remove("MySharedMemory"); }
} remover;
//Create a new segment with given name and size
boost::interprocess::managed_shared_memory segment(boost::interprocess::create_only,
"MySharedMemory", 65536);
//Initialize shared memory STL-compatible allocator
const ShmemAllocator allocator(segment.get_segment_manager());
ShmVector* v = segment.construct<ShmVector>("ShmVector")(allocator);
v->push_back(1); v->push_back(2); v->push_back(3);
//Launch child process
std::string s(argv[0]); s += " child ";
if(0 != std::system(s.c_str()))
return 1;
} else { // Child process
//Open the managed segment
boost::interprocess::managed_shared_memory segment(
boost::interprocess::open_only, "MySharedMemory");
//Find the vector using the c-string name
ShmVector *v = segment.find<ShmVector>("ShmVector").first;
for (const auto& i : *v) {
std::cout << i << " ";
}
std::cout << std::endl;
}
}
根据标准,应该没问题。 – Xeo 2013-03-08 16:01:25
@Xeo我不太确定。该标准指出,STL实现可以自由地假定相同类型的分配器可以释放内存;大多数实现并不依赖于此,但应该检查'std'库的文档。但是,考虑到'g ++'和'libstdC++'的流行,如果Boost没有明确提醒您不兼容,我会感到惊讶。 – 2013-03-08 16:19:16
@Xeo我在标准中发现,子弹3对于所有std :: containers都是正确的:23.2.1.3。但是找不到子弹1和2的任何东西。 – 2013-03-08 16:50:37