Preventing Evil Operator Overloading

While doing some research on allocators, I noticed that the language specification has some interesting wording with regards to getting the address of an element from an allocator. Specifically, it says (Section 20.6.9.1 Clauses 2 & 3):

Returns: The actual address of the object referenced by x, even in the presence of an overloaded operator&.

How do you do that?

It turns out to be a bit more simple than you might think. The basic idea is to trick the compiler into thinking the object type is something “safe”, and from there we can get the address. The safest thing for you to trick the compiler into thinking is that you’ve got a reference to a char, since that’s always a defined operation. Then you can get the address of the char& via the usual means without having to worry about the overloaded operator being called.

template <typename T>
T *safe_address( T& foo ) {
  return ((T *)&(char &)foo);
}

The magic here is that the function receives a reference to the type, it casts that to a char&, then takes the address of the character reference. From there, it typecasts the results back into a pointer to the type. Et voila, you’ve got a safe way to get the pointer without worrying about overloaded operators!

It turns out that the STL already has a helper function for you, called std::addressof. But now you know how it’s implemented too.

This entry was posted in C/C++ and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published.