如何在boost共享内存段中的共享数据上保留指针?
我有一个函数返回:
shm.construct<SharedData>(_nameSeg.c_str())(innerDataAllocator);
但是在函数之外,SharedData指向的对象不可访问。为什么?
我的一般问题是我希望有一种获取方法,并在共享内存中设置数据,但是每次都不必:
所以我想做的是存储在结构中:
这是一个好主意/设计吗? 我该怎么办?
编辑
这是我想要的类的类型,它是一个单例,用于存储当前shm的信息:
typedef bip::allocator<wchar_t, bip::managed_shared_memory::segment_manager> CharAllocator;
typedef bip::basic_string<wchar_t, std::char_traits<wchar_t>, CharAllocator> MyShmString;
class InnerData {
public:
uint64_t id;
MyShmString name;
uint8_t status;
static const uint8_t defaultStatus = 3;
InnerData(CharAllocator cAlloc):name(cAlloc) {
}
};
typedef bip::allocator<InnerData, bip::managed_shared_memory::segment_manager> InnerDataAllocator;
class Zone {
public:
SharedData * sharedData;
CharAllocator charAllocator;
InnerDataAllocator innerDataAllocator;
Zone():{} //here I need to initialize charAllocator and innerDataAllocator with shm.get_segment_manager(),
// because bip::allocators don't have default constructors
static Zone create(std::string &_name, std::string &_nameSeg);
static Zone get(std::string &_name, std::string &_nameSeg);
static Zone delete(std::string &_name, std::string &_nameSeg);
void putInShm(const std::vector<UsualInnerData> &in);
static bool alreadyCreated;
};
.cpp
Zone::create(std::string &_name, std::string &_nameSeg){
//create the shm
// create allocators charAllocator and innerDataAllocator, passing shm.get_segment_manager()
//construct the sharedData object (with shm.construct<SharedData>(_nameSeg.c_str())(innerDataAllocator))
//create a Zone
Zone z(charAllocator, innerDataAllocator, sharedData );
return z;
}
在这种情况下,区域构造函数为:
Zone(CharAllocator _charAllocator, InnerDataAllocator _innerDataAllocator, SharedData* _sharedData):
charAllocator(_charAllocator),
innerDataAllocator(_innerDataAllocator),
sharedData(_sharedData)
{}
但是,正如我所说,一旦我们退出Zone :: Create,SharedData指针(位于返回的Zone z内)所指向的数据便被取消分配了内存。
第二个问题是在Zone :: putInShm:
void Zone::putInShm(const std::vector<UsualInnerData> &in){
InnerData newInnerData (charAllocator);
MyShmString newShmString(charAllocator)
for (auto a : in) {
newInnerData.id = a.id;
newShmString = a.name.c_str();//Here I get an access violation, which means charAllocator is bad ?
newInnerData.name = newShmString
sharedData->data.push_back(newInnerData);
}
return;
}
编辑2:
这是最小的可编译代码。它重现上述错误: https://uploadfiles.io/8o8zo 密码:stackoverflow