我只是使用boost :: interprocess :: managed_shared_memory在内存中创建共享向量,我已经成功创建了共享内存,我发现当我读取向量时,可以读取和打印所有元素注释1中的向量,但是当离开向量g / gr的初始化范围时,即在main函数中,我不能再访问向量内容了,程序说地址映射错误,但是地址是一样的,为什么?谁有人回答?谢谢!
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
typedef boost::interprocess::allocator<boost::interprocess::vector<int>, boost::interprocess::managed_shared_memory::segment_manager> ShmemAllocator;
typedef boost::interprocess::vector<boost::interprocess::vector<int>, ShmemAllocator> Shmem2DVector;
class TestVector{
public:
Shmem2DVector *g;
Shmem2DVector *gr;
TestVector{
boost::interprocess::managed_shared_memory segment(boost::interprocess::open_only, "shmem");
g = segment.find<Shmem2DVector>("myVector").first;
gr = segment.find<Shmem2DVector>("myVector").first;
//1. print vector g/gr and size of vector g/gr
}
};
int main(){
TestVector test_vec();
//2. print vector g/gr and size of vector g/gr
return 0;
}
答案 0 :(得分:0)
一旦离开构造函数,managed_shared_memory对象就会被销毁。 尝试将您的班级定义更改为以下内容:
class TestVector
{
public:
Shmem2DVector *g;
Shmem2DVector *gr;
TestVector()
: segment(boost::interprocess::open_only, "shmem")
{
g = segment.find<Shmem2DVector>("myVector").first;
gr = segment.find<Shmem2DVector>("myVector").first;
}
private:
boost::interprocess::managed_shared_memory segment;
};