ZFY*_*ZFY 5 c++ boost pointers boost-interprocess
我想要的是使用名为ShmObj的类访问托管共享内存对象的数据信息,其中指向共享对象的原始指针作为私有成员,如下面的代码块.
我的问题是主程序分段错误.我猜绝对原始指针会导致问题.我试图将原始指针更改为bi :: offset_ptr,但没有帮助.任何帮助表示赞赏.
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;
};
Run Code Online (Sandbox Code Playgroud)
main.cpp中
#include "ShmObj.h"
#include <iostream>
int main() {
ShmObj X;
std::cout << X.getNumber() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
您的共享内存段在构造函数末尾被破坏...将其移动到一个字段以延长其生命周期:
#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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1008 次 |
| 最近记录: |