已分配空间中的链表

Linked list in allocated space?

本文关键字:链表 空间 分配      更新时间:2023-10-16

我希望这个问题不需要过多的讨论,而是需要一个明确的答案。

我在大学里学了C,然后开始写我的第一个有用的程序(意思是没有规范)。我只是偶然发现了一个问题,我到目前为止还没有处理过,我想他们在讲座中没有提到:

当我分配可能被调整大小的内存时,我不应该存储指向该分配空间地址的指针。因为当我重新分配时,空间可能会被移动到另一个位置,这使得指向该区域的每个指针都毫无价值。这让我得出结论,我不能在空间中存储链表,每个元素都"存在"在这个空间的某个地方,因为重新分配可能会使所有的"next"answers"prev"指针失效。

这是一个问题,我从来没有遇到过,这就是为什么我想问你是否有一些解决方案。具体来说:我有一个共享内存区域,并希望将所有数据存储在其中,以便不同的进程可以在其中工作。由于数据(字符串)将被频繁地添加和删除,并且必须按照特定的顺序,我认为链表将是最好的方法。现在我意识到我不能这样做。还是我太盲目,看不到显而易见的解决方案?你会怎么做呢?(我不想把所有的东西都存储在一个文件中,它应该留在(主)内存中)

感谢并致以最良好的问候。菲尔。

可以以牺牲简单性和性能为代价来完成。与在共享内存中存储指针不同,您必须存储从区域开始的偏移量。然后,当您想要"解引用"其中一个时,您可以将偏移量添加到指向共享区域的指针上。

为了避免错误,我会根据实际使用的语言为其创建一个特殊类型

C

 //seriously, this is one situation where I would find a global justified
 region_ptr region;
 //store these instead of pointers inside the memory region
 struct node_offset {ptrdiff_t offset};
 //used to get a temporary pointer from an offset in a region
 //the pointer is invalidated when the memory is reallocated
 //the pointer cannot be stored in the region
 node* get_node_ptr(node_offset offset) 
 {return (node*)((char*)region+offset.offset);}
 //used to get an offset from a pointer in a region
 //store offsets in the region, not pointers
 node_offset set_node_ptr(region* r, node* offset) 
 {node_offset o = {(char*)offset.offset-(char*)region}; return o;}
c++

 //seriously, this is one situation where I would find a global justified
 region_ptr region;
 //store these in the memory region
 //but you can pretend they're actual pointers
 template<class T>
 struct offset_ptr { 
     offset_ptr() : offset(0) {}
     T* get() const {return (T*)((char*)region + offset);}
     void set(T* ptr) {offset = (char*)ptr - (char*)region;}
     offset_ptr(T* ptr) {set(ptr);}
     offset_ptr& operator=(T* ptr) {set(ptr); return *this;}
     operator T*() const {return get();}
     T* operator->() const {return get();}
     T& operator*() const {return *get();}
 private:
     ptrdiff_t offset;
 };
 template<class T>
 struct offset_delete {
     typedef offset_ptr<T> pointer;
     void operator()(offset_ptr<T> ptr) const {ptr->~T();}
 };
 //std::unique_ptr<node, offset_delete<node>> node_ptr;

另一种与Mooing Duck建议的偏移量方法非常相似的方法是数组和数组索引。

如果每个列表元素的大小相同,则声明一个指向这些列表元素的数组的指针。将该指针设置为内存区域的开头。存储数组偏移量,而不是prev和next节点的指针。现在编译器会帮你添加偏移量