0

Boost provides a relative offset pointer (boost::interprocess::offset_ptr) which can be used in place of regular of a raw pointer in STL containers with an appropriate allocator (see this question for one reason why this is useful).

A concise explanation of how this type of pointer can be implemented (taken from this not boost specific answer) is:

template<class T> class offset_ptr {
    size_t offset; public:
    T* operator->() { return reinterpret_cast<T*>(reinterpret_cast<char*>(this)+offset); } };

This is very clever. It enables you to use containers in shared memory and to persist structures to disk.

This idea is very old, very clever, very simple and very useful. This begs the question why is there no such pointer provided in the current ISO C++ standard.

Allocator_traits supports providing your own pointer types in place of a raw pointer.

boost::interprocess::offset_ptr is even explicitly referenced on cppreference as a good example of why allocator traits allows this.

What obstacles remain to adding such a type?

See also:

Towards meaningful fancy pointers explores this but does not quite explain it.

Bruce Adams
  • 4,953
  • 4
  • 48
  • 111
  • 2
    "What obstacles remain to adding such a type?" Someone writing a proposal, and the committee voting to accept it. – Caleth May 20 '22 at 09:32
  • Just as an aside on the "containers in shared memory" bit, Boost.Interprocess has [a nice way of doing this](https://www.boost.org/doc/libs/release/doc/html/interprocess/allocators_containers.html). – DevSolar May 20 '22 at 09:34
  • 1
    Just use the boost version, why do you need a standard one? I don't think bloating the standard library with specialized classes is a good idea. That's what 3rd party libraries are for. – Aykhan Hagverdili May 20 '22 at 09:35
  • For the same reason we need any standards at all. The point in this case is that it is not that specialised. It is quite widely used and thus many would benefit. The boost version isn't the only one. By the standards of what is going into ISO C++. This seems like low hanging fruit. That the committee has not attempted to standardise it yet suggests it might actually be more prickly. – Bruce Adams May 20 '22 at 09:42
  • Pointer arithmetic is limited. The standard does not assume a memory model that allows every two pointers to be subtracted for offsets. Even `std::less` for pointers must be specified essentially as "magic". – StoryTeller - Unslander Monica May 20 '22 at 09:55
  • @StoryTeller-UnslanderMonica that might be the answer. But use of offset_ptr assumes its not just two arbitrary pointers but two pointers to a contiguous block of memory. – Bruce Adams May 20 '22 at 09:58
  • Is this what you're looking for? https://stackoverflow.com/questions/54737556/set-shared-ptr-with-new-pointer-that-is-old-pointer-offset – Galik May 20 '22 at 10:33
  • @Galik nope. That is completely unrelated. – Bruce Adams May 20 '22 at 11:02

0 Answers0