简体   繁体   中英

Boost::interprocess managed_shared_memory pointer effective scope

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM