【发布时间】:2018-01-10 06:41:09
【问题描述】:
以下程序在内存映射文件的空间内为c(C 类型的对象)分配内存。向c 中包含的向量添加单个字符会将向量报告的大小从 0 更改为 18446744073709551520。
#include <iostream>
#include <new>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/offset_ptr.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
using namespace boost::interprocess;
class C;
typedef managed_mapped_file::segment_manager SegmentManager;
typedef allocator<void, SegmentManager> VoidAllocator;
typedef allocator<char, SegmentManager> CharAllocator;
typedef allocator<C, SegmentManager> CAllocator;
typedef offset_ptr<C> CPtr;
class C {
public:
std::vector<char, CharAllocator> data;
C(const VoidAllocator &voidAlloc) : data(voidAlloc) {}
void add_char() {
std::cout << data.size() << std::endl;
data.push_back('x');
std::cout << data.size() << std::endl;
}
};
int main(int argc, char *argv[]) {
boost::filesystem::remove_all("file");
managed_mapped_file segment(create_only, "file", 100000);
VoidAllocator allocator_instance(segment.get_segment_manager());
CAllocator alloc_c(allocator_instance);
CPtr c = alloc_c.allocate_one();
*c = C(allocator_instance);
c->add_char();
return 0;
}
当c在堆栈上分配而不是动态分配时,不会出现该问题。
C c(allocator_instance);
c.add_char();
我在 Debian GNU/Linux 上使用 Boost 1.62 和 g++ 6.3.0-18 使用以下命令编译代码。
g++ -Wall -pthread -lboost_system -lboost_filesystem t.cpp -o t
【问题讨论】:
标签: c++ vector boost allocator