I wish to create a static Class object which should stay in the memory while the program is running. The object needs to be initialized only once by the init function and the output function will be called in a static method always. Does my code make sense and is it thread-safe?
class Singleton
{
public:
static void init(const int value)
{
static Singleton inst;
inst.Value = value;
}
static int prnValue()
{
return Value;
}
private:
Singleton() {};
static int Value;
};
int main()
{
int inputValue = 10;
Singleton::init(inputValue);
cout << Singleton::prnValue();
return 0;
}
New Edit: Or can I try like this then?
class Singleton
{
public:
static Singleton& init(const int value)
{
static Singleton inst;
inst.Value = value;
return inst;
}
static int prnValue()
{
return Value;
}
private:
Singleton() {};
static int Value;
};
Addition: Meyer's singleton example look like
class Singleton
{
public:
static Singleton& init()
{
static Singleton inst;
return inst;
}
private:
Singleton() {};
};
So Isn't my code consistent with Meyer's example?
Try4: How about this?
class Singleton
{
public:
static Singleton& init(int value)
{
static Singleton inst(value);
return inst;
}
static int prnValue()
{
return Value;
}
private:
Singleton(value)
{
Value = value;
}
int Value;
};
Added comment: How to pass argument in a singleton seems to provide the same answer as Try4.