Corralx

My slice of reality

A simple Tagged Pointer

So, since you gotta start somewhere, I thought it would have been a lot more interesting to actually begin this new adventure with an actual post, albeit simple, leaving the presentation and every personal information for the About page.

In this post I am going to present a very simple implementation of a tagged pointer in C++11, exploring the design choices and rationale behind it. The complete source can be found on my GitHub here. The only requirement is a fairly recent C++11 compiler with variadic templates and constexpr support. If you encounter any problem or bug using it don’t hesitate contacting me using the social buttons on top or by opening a GitHub issue!

So, what is it?

Generally speaking, a tagged pointer is just a raw pointer to a memory address with any type of additional data (hereafter called tag) added to it, which carries some special meaning for us. We can actually think of three ways to implement this generic idea:

  • Use a struct to store both the pointer and the tags. While this is the simpler approach and it poses no restriction on the amount of data associated to it, it’s just a plain object (and we are obviously not going down this road)
struct tagged_pointer
{
  object_type* pointer;
  bool dirty_flag;
  bool writable_flag;
};
  • Set the value of the pointer to some sentinel value, and test for it accordingly in your code. This is similar to check for null pointers using 0 as an invalid address, but it is not really useful since you can use this approach only when you don’t care anymore about the value of the pointer itself
  • Exploit the alignment of data in memory and reuse the lower bits of pointers to save our tags. This is clearly architecture/compiler dependent and a lot of things may break. For this reason we’ll obviously go down this road.
Read more Comment