I learned long ago that the only reliable way for a static member of be initialized for sure is to do in a function. Now, what I’m about to do is to start returning static data by non-const reference and I need someone to stop me.
function int& dataSlot()
{
static int dataMember = 0;
return dataMember;
}
To my knowledge this is the only way to ensure that the static member is initlized to zero. However, it creates obscure code like this:
dataSlot() = 7; // perfectly normal?
The other way is to put the definition in a translation unit and keep the stuff out of the header file. I have nothing against that per se but I have no idea what the standard says regard when and under what circumstances that is safe.
The absolute last thing I wanna end up doing is accidently accessing uninitialized data and losing control of my program.
Returning a non-const reference in itself is fairly harmless, for example it’s what
vector::at()does, orvector::iterator::operator*.If you don’t like the syntax
dataSlot() = 7;, you could define:Or you could define:
If you want someone to stop you, they need more information in order to propose an alternative to your use of mutable global state!