【问题标题】:boost interprocess managed shared memory raw pointer as a class member将进程间管理的共享内存原始指针提升为类成员
【发布时间】:2014-06-03 02:44:28
【问题描述】:

我想要的是使用名为 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;
};

ma​​in.cpp

#include "ShmObj.h"
#include <iostream>

int main() {
    ShmObj X;
    std::cout << X.getNumber() << std::endl;
}

【问题讨论】:

    标签: c++ pointers boost boost-interprocess


    【解决方案1】:

    您的共享内存段在构造函数结束时被破坏...将其移至字段以延长其生命周期:

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

    【讨论】:

    • 为什么我们不能在初始化列表中也做pNum(segment.find_or_construct&lt;int&gt;("Number")(0))
    • 可以,你试过吗?无论如何,对于任何重要的事情,我真的不会在初始化器列表中这样做,除非你有一个合适的 Rule-Of-Zero 资源包装器以使其异常安全,如果施工投掷。考虑:paste.ubuntu.com/8552394
    猜你喜欢
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多