Re: static class member, inline getter and initialization
Am 03.12.2012 22:15, schrieb dakron:
There is a code like that:
-----------------------------
//myclass.h
#include "mypodclass.h"
class MyClass
{
inline static MyPODClass instance() { return _instance; }
private:
static MyPODClass _instance;
};
//myclass.cpp
MyPODClass MyClass::_instance;
-----_----------------------
Is it guaranteed that everywhere where the instance() (inlined method) is
used _instance is properly initialized?
Definitively *not* so! The initialization of MyClass::_instance has no
relation to any call of MyClass::instance.
I suspect that if the instance() was
not inlined and its implementation was in myclass.cpp translation unit then
it should be fine. But I am not sure if presented code is safe from the
initialization point of view assuming that instance() is invoked everywhere
(differenct static object, threads etc. basically worst case scenario).
Multithreading aside, the above definition does not ensure proper
initialization of the static data member. This initialization of this
member in above context shows the same ordering sensitivity as any other
global object.
If your really want to use a singleton, you should use the idiom of
"Meyers singleton", see e.g.
http://www.devarticles.com/c/a/Cplusplus/C-plus-plus-In-Theory-The-Singleton-Pattern-Part-I/4/
or a Schwarz-counter approach, see e.g.
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]