gpt4 book ai didi

c++ - 在共享内存中使用自定义分配器实例化类

转载 作者:太空宇宙 更新时间:2023-11-04 12:26:06 40 4
gpt4 key购买 nike

由于以下问题,我正在拉头发:我正在关注 the example在 boost.interprocess 文档中给出实例化我在共享内存中编写的固定大小的环形缓冲区缓冲区类。我的类的骨架构造函数是:

template<typename ItemType, class Allocator >
SharedMemoryBuffer<ItemType, Allocator>::SharedMemoryBuffer( unsigned long capacity ){

m_capacity = capacity;

// Create the buffer nodes.
m_start_ptr = this->allocator->allocate(); // allocate first buffer node
BufferNode* ptr = m_start_ptr;
for( int i = 0 ; i < this->capacity()-1; i++ ) {
BufferNode* p = this->allocator->allocate(); // allocate a buffer node
}
}

我的第一个问题:这种分配是否保证缓冲区节点分配在连续的内存位置,即当我尝试从地址 m_start_ptr + n*sizeof(BufferNode) 访问第 n 个节点时在我的 Read()方法行得通吗?如果不是,有什么更好的方法来保留节点,创建链表?

我的测试工具如下:

// Define an STL compatible allocator of ints that allocates from the managed_shared_memory.
// This allocator will allow placing containers in the segment
typedef allocator<int, managed_shared_memory::segment_manager> ShmemAllocator;

//Alias a vector that uses the previous STL-like allocator so that allocates
//its values from the segment
typedef SharedMemoryBuffer<int, ShmemAllocator> MyBuf;

int main(int argc, char *argv[])
{
shared_memory_object::remove("MySharedMemory");

//Create a new segment with given name and size
managed_shared_memory segment(create_only, "MySharedMemory", 65536);

//Initialize shared memory STL-compatible allocator
const ShmemAllocator alloc_inst (segment.get_segment_manager());

//Construct a buffer named "MyBuffer" in shared memory with argument alloc_inst
MyBuf *pBuf = segment.construct<MyBuf>("MyBuffer")(100, alloc_inst);
}

这给了我与最后一条语句的模板相关的各种编译错误。我究竟做错了什么?是segment.construct<MyBuf>("MyBuffer")(100, alloc_inst)提供两个模板参数的正确方法?

最佳答案

My first question: Does this sort of allocation guarantee that the buffer nodes are allocated in contiguous memory locations, i.e. when I try to access the n'th node from address m_start_ptr + n*sizeof(BufferNode) in my Read() method would it work?

没有。原因是您只有第一个节点。您创建的所有 BufferNode 对象都不会被保存(例如,以链表方式)并导致内存泄漏。此外,这种分配方式不能保证连续的内存位置。随机访问(如您稍后在问题中所述)很可能会失败。要获得连续的内存,您需要创建一个包含 BufferNode 对象的数组(可能是动态的)。

This gives me all kinds of compilation errors related to templates for the last statement. What am I doing wrong?

在不知道实际错误的情况下很难说。此外,您是否了解您的代码(以及 Boost::Interprocess 的适用方式或分配器的工作方式)?

请注意,您引用的示例创建了一个 vector,保证其包含的对象具有连续的内存。这里唯一的区别是对象是在共享内存段上创建的,而不是在自由存储区上创建的,当您没有将分配器指定为第二个参数并使用默认分配器时,通常会发生这种情况。

关于c++ - 在共享内存中使用自定义分配器实例化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2436499/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com