Introduction
Recently I stumbled upon a task of adding a unique identifier to classes (not instances!) in my project (why I needed that is a different question with too long an answer to discuss here). Those identifiers didn't need to be consistent from run to run, nor did they need to have any specific values - just uniqueness within one run was enough.
There are quite a few ways to achieve that, but I wanted the one that requires the least amount of coding, provides ID of an integer type (for performance reasons, because it was later used as a key in the map), and doesn't clutter my classes too much with extra data or code.
Quick Googling gave me an elegant solution. The key idea is that functions should have some entry address, which means - this is unique, integer information. So, the original code looked like this:
#define ADD_UNIQUE_ID \
private: \
static const size_t getUniqueIdPrivate()
{ return reinterpret_cast<size_t>(&getUniqueIdPrivate); } \
public: \
virtual const size_t getUniqueId() const {return getUniqueIdPrivate();};
And usage looked like this:
class A
{
.....
ADD_UNIQUE_ID
};
class B: public A
{
.....
};
class C: public B
{
.....
ADD_UNIQUE_ID
};
Well, this worked perfectly in debug mode. Happy, I switched to release mode, and all of a sudden, getUniqueId()
started to return the very same value. What happened?!
Few hours later, and looking at assembler code, I found the answer: "COMDAT folding". Linker was too smart - it figures out that function body is the same all the time, so it moves all getUniqueIdPrivate()
function to the same address. Bummer.
So, the solution was to add different code to each of those static
functions. Note that we never call this function directly, we just take its address, so code inside can be inefficient enough, we just need to make sure that final COMDAT code is different. And, here is the final code:
#define ADD_UNIQUE_ID \
private: \
static void getUniqueIdPrivate() { std::string val(_T(__FILE__));
volatile int val2 = __LINE__ ; UNREFERENCED_PARAMETER(val);
UNREFERENCED_PARAMETER(val2);} \
public: \
virtual inline const size_t getUniqueId() const
{return reinterpret_cast<size_t>(getUniqueIdPrivate);};
It was tested in debug/release x32/x64 on VC9, VC10 and VC11. If someone will bother to test it in other compilers, please comment.