Private Static Variable Initialization (redux)
Jun 17, 2014 at 5:59pm UTC
This is actually an added answer to a closed question.
TaylorCoons8798 wrote this:
http://www.cplusplus.com/forum/beginner/125835/
I wanted to add that if you wish to provide a static variable without using an implementation file (.cpp), try playing with the following idiom (within your header file):
1 2 3 4 5
inline my_object& get_var()
{
static my_object ob;
return obj;
}
This returns a reference to the singular instance of 'ob', maintaining any changes made to its state.
This is a variation of another idiom many people use to help create singletons (classes that only have a single instance):
1 2 3 4 5 6 7 8 9 10 11 12 13
class my_class
{
public :
static my_class& get_my_class()
{
return _singleton;
}
private :
my_class(){}
private :
static my_class _singleton;
};
The code above makes it so you may only acquire an instance of my_class by calling my_class::get_my_class(), effectively making my_class a singleton.
I hope this is useful.
Topic archived. No new replies allowed.