Pointer Tagging in C++: The Art of Packing Bits into a Pointer
5 hours ago
- #Memory Optimization
- #Pointer Tagging
- #C++
- 64-bit pointers have unused bits (16 high bits and 4 low bits) that can be repurposed for storing extra data.
- Pointer tagging is used in dynamic type information, tree-like data structures, and dynamic polymorphism to save memory and speed up operations.
- Chrome's V8 engine and Objective-C use pointer tagging to distinguish between raw integers and heap-allocated objects.
- The Linux kernel uses a bit in parent pointers of red-black tree nodes to determine node color.
- PBRT uses tagged pointers to reduce dynamic dispatch overhead by avoiding per-object v-tables.
- A C++ implementation of tagged pointers involves bitwise operations to pack and unpack data from the pointer.
- Tagged unions can use pointer tagging to store type information in the pointer itself, reducing memory usage.
- Hardware features like AMD's UAI, Intel's LAM, and ARM's TBI support storing metadata in pointer bits without affecting address translation.