Boost::interprocess managed_shared_memory pointer effective scope

261 views Asked by At

I just use boost::interprocess::managed_shared_memory to create a shared vector in memory, I have successfully created the shared memory, I find when I read the vector, it's ok to read and print all elements in the vector in comment 1, but when leaving the scope of initialization of vector g/gr, namely, in the main function, I cannot access the vector content anymore, the program says address mapped error, but the address is the same, so why? could anyone answer? Thanks!

#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;
}
1

There are 1 answers

0
NovicePhantasm On

As soon as you leave the constructor, the managed_shared_memory object is destroyed. Try to change your class definition to the following:

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;        
};