Boost logo

Boost :

Subject: [boost] interest in a stateful pointer library?
From: Hans Dembinski (hans.dembinski_at_[hidden])
Date: 2017-10-02 08:46:32


Hi everyone,

I wrote a variant of std::unique_ptr, called tagged_ptr, which allows safe read/write access to a customisable number of bits in the pointer variable. You can find the library on github:

https://github.com/HDembinski/stateful_pointer

You can use those bits to store extra state in the pointer variable at no extra space cost. I did some benchmarks to show that the computational overhead required for the bit manipulation is also negligible.

One needs little imagination to find good use for those bits. As a proof of principle, I wrote an STL compatible string class which has the size of const char*, but can store up to 7 ASCII characters (on a 64 bit system) without allocating any memory on the heap (aka small string optimisation). The string class is also included in the library. To make this work, I use one of the bits in the pointer variable to recognise whether the variable should be interpreted as a pointer or as a char array.

The Stateful Pointer library is C++11, header-only, and AFAIK platform-independent (in theory, this has not been tested so far). To create pointers which allow one to use a certain number of bits for other purposes, I rely on Boost.Align to allocate aligned memory.

How does it work? Aligned memory, as the name implies, does not point to any address in memory, only certain addresses are allowed. For example, a two-byte aligned memory block can only have an even address. Therefore the lowest bit in the address is always zero. Since the bit is guaranteed to be zero, we can use it to store something else and mask it to zero whenever we need to dereference the pointer.

I think this is a generally useful class to have in Boost, so is there some interest in polishing it up in a review process?

Best regards,
Hans


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk