C++:提升进程间内存映射文件错误

C++: Boost interprocess memory mapped file error

我正在尝试使用 答案创建内存映射文件,但出现编译错误。这是我的代码:

namespace bi = boost::interprocess;
std::string vecFile = "vector.dat";
bi::managed_mapped_file file_vec(bi::open_or_create,vecFile.c_str(), sizeof(struct Rectangle) * data_size);

typedef bi::allocator<struct Rectangle, bi::managed_mapped_file::segment_manager> rect_alloc;
typedef std::vector<struct Rectangle, rect_alloc>  MyVec;

MyVec * vecptr = file_vec.find_or_construct<MyVec>("myvector")(file_vec.get_segment_manager());

vecptr->push_back(random_rectangle);

结构是这样的:

struct Rectangle{

  Rectangle(float *minArr, float *maxArr, int arr, int exp, int ID){
    this->arrival = arr;
    this->expiry = exp;
    this->id = ID;
    for(int i=0; i < 2; i++){
      min[i] = minArr[i];
      max[i] = maxArr[i];
    }

  int arrival, expiry, id;
  float min[2];
  float max[2];
}

我得到的错误是:编译器无法从 'boost::interprocess::offset_ptr' 中推断出“_Ty*”的模板参数。我做错了什么?

我觉得还行:

Live On Coliru

#include <boost/interprocess/managed_mapped_file.hpp>
#include <vector>

namespace bi = boost::interprocess;

struct Rectangle {
    Rectangle(float *minArr, float *maxArr, int arr, int exp, int ID) {
        this->arrival = arr;
        this->expiry = exp;
        this->id = ID;
        for (int i = 0; i < 2; i++) {
            min[i] = minArr[i];
            max[i] = maxArr[i];
        }
    };

    int arrival, expiry, id;
    float min[2];
    float max[2];
};

namespace Shared {
    using segment = bi::managed_mapped_file;
    using mgr     = segment::segment_manager;

    using alloc   = bi::allocator<Rectangle, mgr>;
    using vector  = std::vector<Rectangle, alloc>;
}

Rectangle random_rectangle() { 
    float dummy[2] = { };
    return { dummy, dummy, 0, 0, 0 }; 
}

int main() {
#define data_size 10
    std::string vecFile = "vector.dat";
    Shared::segment mmem(bi::open_or_create, vecFile.c_str(), (10u<<10) + sizeof(struct Rectangle) * data_size);

    Shared::vector *vecptr = mmem.find_or_construct<Shared::vector>("myvector")(mmem.get_segment_manager());

    vecptr->push_back(random_rectangle());
}

如果它不能完全按照上面的方式编译,请注意您的库和编译器的版本。考虑升级。