boost interprocess managed shared memory raw pointer as a class member
boost, boost-interprocess, c++, pointers
Solution
Your shared memory segment is destructed at the end of the constructor... Move it to a field to extend its lifetime:
#include <string>
#include <boost/interprocess/managed_shared_memory.hpp>
namespace bi = boost::interprocess;
class ShmObj {
public:
ShmObj()
: segment(bi::open_or_create, "shm", 32ul*1024),
pNum(0)
{
pNum = segment.find_or_construct<int>("Number")(0);
}
int getNumber() {
assert(pNum);
return *pNum;
}
virtual ~ShmObj() {}
private:
bi::managed_shared_memory segment;
int* pNum;
};
#include <iostream>
int main() {
ShmObj X;
std::cout << X.getNumber() << std::endl;
}
Problem
What I want is to access the data info of an managed shared memory object using a class named ShmObj with the raw pointer to the shared objects as private member, as code blocks below. My problem is the main program segmentation fault. I guess the absolute raw pointer causes the problem. I tried to change the raw pointer to bi::offset_ptr but doesn't help. Any help is appreciated. ShmObj.h ``` #include <string> #include <boost/interprocess/managed_shared_memory.hpp> namespace bi = boost::interprocess; class ShmObj { public: ShmObj() { bi::managed_shared_memory segment(bi::open_only, "shm"); pNum = segment.find<int>("Number").first; } int getNumber() {return *pNum;} virtual ~ShmObj() {} private: int* pNum; }; ``` main.cpp ``` #include "ShmObj.h" #include <iostream> int main() { ShmObj X; std::cout << X.getNumber() << std::endl; } ```