cpp / expert
Snippet
Bit-level Metadata Embedding in Pointers
Since pointers on modern systems are often aligned to 4 or 8 bytes, the lowest bits are always zero. This snippet exploits this to store additional metadata (a 'tag') directly inside the pointer itself, reducing memory footprint in complex data structures like trees or graphs.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdint>template <typename T>class TaggedPointer {uintptr_t raw;static constexpr uintptr_t MASK = 0x03;public:TaggedPointer(T* ptr, uint8_t tag) {raw = reinterpret_cast<uintptr_t>(ptr) | (tag & MASK);}T* getPointer() const {return reinterpret_cast<T*>(raw & ~MASK);}uint8_t getTag() const {return static_cast<uint8_t>(raw & MASK);}};
Breakdown
1
uintptr_t raw;
Uses an unsigned integer type large enough to hold a pointer address.
2
raw & ~MASK
Applies a bitmask to clear the tag bits and retrieve the original memory address.
3
tag & MASK
Ensures the tag value only occupies the allowed lower bits to avoid corrupting the address.