gpt4 book ai didi

c++ - 为什么花哨的指针存在?

转载 作者:行者123 更新时间:2023-12-02 10:00:33 28 4
gpt4 key购买 nike

我一直将指针视为迭代器的一种特殊形式,用于在对象连续存储在内存中的特殊情况下。但是,我发现Allocator成员类型pointer(然后在迭代器和容器上定义了相同的成员类型)不需要是真正的指针,但是根据cppreference,它可能是所谓的花式指针,

is used to access objects allocated in address spaces that differ from the homogeneous virtual address space.


这就是我过去所说的迭代器,而不是指针,但这不是重点。我想知道如何不需要分配器分配连续的内存。想象将一个自定义分配器传递给 std::vector,它不会以连续的方式分配对象。对我而言,这已不再是媒介。如果我不希望对象在内存中是连续的,请使用列表而不是带有自定义分配器的 vector 。它们看起来像是造成困惑的一大根源,为什么要引入它们呢?

最佳答案

I've always seen pointers as a specialization of iterators


数组的迭代是指针的用途之一。这不是他们的唯一目的。它们还用作标识动态分配的“句柄”。

why were [fancy pointers] introduced?


您链接的页面说明了其介绍的原因:

Such pointers were introduced to support segmented memory architectures ...


如今,这样的体系结构非常罕见,但是程序员发现了其他用例:

... and are used today to access objects allocated in address spaces that differ from the homogeneous virtual address space that is accessed by raw pointers. An example of a fancy pointer is the mapping address-independent pointer boost::interprocess::offset_ptr, which makes it possible to allocate node-based data structures such as std::set in shared memory and memory mapped files mapped in different addresses in every process.


链接页面中链接的标准纸张 P0773R0具有更详细的用途列表:
  • Scenario A. "Offset" pointers with a modified bit-level representation.
  • Scenario B. Small-data-area "near" pointers.
  • Scenario C. High-memory-area "far" pointers.
  • Scenario D. "Fat" pointers carrying metadata for dereference-time.
  • Scenario E. "Segmented" pointers carrying metadata for deallocate-time.

请注意,并非所有标准库实现都支持P0773R0中探讨的所有标准容器的花式指针的所有用例。

关于c++ - 为什么花哨的指针存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62700637/

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