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.

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.

Your email address will not be published. Required fields are marked *

Comment

Name *

Email *

Website

Who

Aaron Ballman is a software engineer for GrammaTech. He has almost two decades of experience writing cross-platform frameworks in C/C++, compiler & language design, and software engineering best practices and is currently a voting member of the C (WG14) and C++ (WG21) standards committees.

In case you can't figure it out easily enough, the views expressed here are my personal views and not the views of my employer, my past employers, my future employers, or some random person on the street. Please yell only at me if you disagree with what you read.