Singleton file static vs class private static - c++

Is there any difference or specific advice when it comes to the following approaches for defining singletons?
In 1, the singleton object is a class private static, but in 2, it's a file static.
Note: m_initedObj1 is just there to show that class has state, and use case is to call this singleton->DoSomething() many times, without needing to init this object again.
1)
// header file
class Foo {
private:
static Foo* s_fooSingleton;
Foo();
Obj1 m_initedObj1;
public:
static Foo* Singleton();
static void ClearSingleton();
Bar DoSomething(...);
};
// cpp file
Foo* Foo::s_fooSingleton = nullptr;
Foo::Foo() { m_initedObj1 = InitObj1Somewhere(); }
/*static*/ Foo* Foo::Singleton()
{
if(!Foo::s_fooSingleton)
Foo::s_fooSingleton = new Foo();
return Foo::s_fooSingleton;
}
/*static*/ void Foo::ClearSingleton()
{
if(Foo::s_fooSingleton)
delete Foo::s_fooSingleton;
Foo::s_fooSingleton = nullptr;
}
Bar Foo::DoSomething(...) { // do something }
2)
// header file
class Foo {
private:
Foo();
Obj1 m_initedObj1;
public:
static Foo* Singleton();
static void ClearSingleton();
Bar DoSomething(...);
};
// cpp file
static Foo* s_fooSingleton = nullptr;
Foo::Foo() { m_initedObj1 = InitObj1Somewhere(); }
/*static*/ Foo* Foo::Singleton()
{
if(!s_fooSingleton)
s_fooSingleton = new Foo();
return s_fooSingleton;
}
/*static*/ void Foo::ClearSingleton()
{
if(s_fooSingleton)
delete s_fooSingleton;
s_fooSingleton = nullptr;
}
Bar Foo::DoSomething(...) { // do something }

As JerryGoyal states in the comments, in 2) other methods in the same .cpp file can modify s_fooSingleton.
On the other hand, they are not both thread-safe. If you don't really mind the clearing (calling ClearSingleton() explicitly), just go with the Scott Meyers' version. Otherwise, go with the double checked locking version.
It's really hard to ensure the safety in case of explicitly deleting. You always have to check whether it's deleted before you access it. If it's a multi-threaded executable, checking and using it must be atomic, because it can be deleted just after checking.
Double checked locking could be used to create and delete the singleton, which ensures you that there is only one instance at a time. Yet, it does not ensure the object really exist, since you may accidentally delete it.
You may use smart pointers to count references and delete it if no references exist.
Or even better, see this answer https://stackoverflow.com/a/15733545/1632887.
I just wouldn't delete it explicitly if I were you!

Maybe this will satisfy you more:
class MyClass1 {
private:
MyClass1(){}
public:
MyClass1& Instance() {
static MyClass1 theSingleInstance;
return theSingleInstance;
}
};
class MyClass2 {
private:
MyClass2() {}
public:
MyClass2* Instance() {
static MyClass2* theSingleInstance = new MyClass2;
return theSingleInstance;
}
};
class MyClass3 {
private:
MyClass3() {}
public:
MyClass3* Instance() {
static MyClass3 theSingleInstance;
return &theSingleInstance;
}
};

Related

Singleton with make_ptr, why not? [duplicate]

I have a singleton class with a private constructor. In the static factory method I do the following:
shared_ptr<MyClass> MyClass::GetInstance()
{
static once_flag onceFlag;
call_once(onceFlag, []() {
if (_instance == nullptr)
_instance.reset(new MyClass());
});
return _instance;
}
If I use
_instance = make_shared<MyClass>();
the code does not compile. My question is: why new can invoke a private constructor but make_shared not?
As mentioned, std::make_shared or its component parts don't have access to private members.
the call_once and once_flag are un-necessary. They are implicit in c++11 static initialisation,
You normally would not want to expose the shared pointer.
class MyClass
{
MyClass() {}
public:
static MyClass& GetInstance()
{
static auto instance = MyClass();
return instance;
}
};
However, there is one case I can imagine where you would want to expose a shared pointer to the impl - this is in the case where the class can choose to 'break off' or 'reset' the impl to a new one. In this case I would consider code like this:
class MyClass2
{
MyClass2() {};
static auto& InternalGetInstance()
{
static std::shared_ptr<MyClass2> instance { new MyClass2 };
return instance;
}
public:
static std::shared_ptr<MyClass2> GetInstance()
{
return std::atomic_load(std::addressof(InternalGetInstance()));
}
static void reset() {
std::atomic_store(std::addressof(InternalGetInstance()),
std::shared_ptr<MyClass2>(new MyClass2));
}
};
However, in the end, it is my view that 'staticness' of a class should be an implementation detail, and unimportant to the user of the class:
#include <memory>
#include <utility>
class MyClass
{
// internal mechanics
struct Impl {
auto doSomething() {
// actual implementation here.
}
};
// getImpl now becomes the customisation point if you wish to change the
// bahviour of the class later
static Impl& getImpl() {
static auto impl = Impl();
return impl;
}
// use value semantics - it makes for more readable and loosely-coupled code
public:
MyClass() {}
// public methods defer to internal implementation
auto doSomething() {
return getImpl().doSomething();
}
};
int main() {
// note: just create objects
auto mc = MyClass();
mc.doSomething();
// now we can pass the singleton as an object. Other functions don't even
// need to know it's a singlton:
extern void somethingElse(MyClass mc);
somethingElse(mc);
}
void somethingElse(MyClass mc)
{
}
Please take VTT's comment seriously.
To your question:
My question is: why new can invoke a private constructor but make_shared not?
The new is actually used within a lambda in a member-function; Well, A lambda defines a local-class, and C++ standards permits a local-class within a member-function to access everything the member-function can access. And its trivial to remember that member functions can access privates..
std::make_shared has no access to the privates of MyClass. It's outside the scope of MyClass
Example:
class X{
X(){};
public:
static X* create(){ // This member-function can access private functions and ctors/dtor
auto lm = [](){ // This lambda inherits the same access of enclosing member-function
return new X();
};
return lm();
}
};
int main(){
auto x = X::create(); //valid;
auto y = new X(); //invalid;
}
You should use Meyers singleton instead. You should ensure that your compiler supports C++11 magic static before.

creating singleton object with shared pointer [duplicate]

I have a singleton class with a private constructor. In the static factory method I do the following:
shared_ptr<MyClass> MyClass::GetInstance()
{
static once_flag onceFlag;
call_once(onceFlag, []() {
if (_instance == nullptr)
_instance.reset(new MyClass());
});
return _instance;
}
If I use
_instance = make_shared<MyClass>();
the code does not compile. My question is: why new can invoke a private constructor but make_shared not?
As mentioned, std::make_shared or its component parts don't have access to private members.
the call_once and once_flag are un-necessary. They are implicit in c++11 static initialisation,
You normally would not want to expose the shared pointer.
class MyClass
{
MyClass() {}
public:
static MyClass& GetInstance()
{
static auto instance = MyClass();
return instance;
}
};
However, there is one case I can imagine where you would want to expose a shared pointer to the impl - this is in the case where the class can choose to 'break off' or 'reset' the impl to a new one. In this case I would consider code like this:
class MyClass2
{
MyClass2() {};
static auto& InternalGetInstance()
{
static std::shared_ptr<MyClass2> instance { new MyClass2 };
return instance;
}
public:
static std::shared_ptr<MyClass2> GetInstance()
{
return std::atomic_load(std::addressof(InternalGetInstance()));
}
static void reset() {
std::atomic_store(std::addressof(InternalGetInstance()),
std::shared_ptr<MyClass2>(new MyClass2));
}
};
However, in the end, it is my view that 'staticness' of a class should be an implementation detail, and unimportant to the user of the class:
#include <memory>
#include <utility>
class MyClass
{
// internal mechanics
struct Impl {
auto doSomething() {
// actual implementation here.
}
};
// getImpl now becomes the customisation point if you wish to change the
// bahviour of the class later
static Impl& getImpl() {
static auto impl = Impl();
return impl;
}
// use value semantics - it makes for more readable and loosely-coupled code
public:
MyClass() {}
// public methods defer to internal implementation
auto doSomething() {
return getImpl().doSomething();
}
};
int main() {
// note: just create objects
auto mc = MyClass();
mc.doSomething();
// now we can pass the singleton as an object. Other functions don't even
// need to know it's a singlton:
extern void somethingElse(MyClass mc);
somethingElse(mc);
}
void somethingElse(MyClass mc)
{
}
Please take VTT's comment seriously.
To your question:
My question is: why new can invoke a private constructor but make_shared not?
The new is actually used within a lambda in a member-function; Well, A lambda defines a local-class, and C++ standards permits a local-class within a member-function to access everything the member-function can access. And its trivial to remember that member functions can access privates..
std::make_shared has no access to the privates of MyClass. It's outside the scope of MyClass
Example:
class X{
X(){};
public:
static X* create(){ // This member-function can access private functions and ctors/dtor
auto lm = [](){ // This lambda inherits the same access of enclosing member-function
return new X();
};
return lm();
}
};
int main(){
auto x = X::create(); //valid;
auto y = new X(); //invalid;
}
You should use Meyers singleton instead. You should ensure that your compiler supports C++11 magic static before.

How to prevent a caller of a method from storing the result in C++

Assume I have a Singleton class. How can I prevent callers from being able to store the result of the call to getInstance() method?
I need this, since the instance of the singleton can be modified during execution and any stored instance in other classes will be invalidated. My solution would be to force all the callers to call getInstance() every time when they want to use the instance of the Singleton.
class Singleton
{
private:
static Singleton* instance;
private:
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = nullptr;
Singleton* Singleton::getInstance()
{
if (instance == nullptr)
{
instance = new Singleton();
}
return instance;
}
class A
{
private:
Singleton* m_singleton;
public:
A()
: m_singleton(Singleton::getInstance()) //This should not be possible
{
}
};
int main()
{
A a;
return 0;
}
How can I achieve this?
You cannot. If your getInstance() returns a pointer or reference, there is no way to prevent the result from being copied into some variable, the same way as you cannot prevent a result of type int or double from being copied.
You could, however, make the functions the singleton provides static:
class SomeSingleton
{
public:
static void foo();
private:
// deleting copy constructor and assignment operator...
static SomeSingleton* getInstance();
};
void SomeSingleton::foo()
{
SomeSingleton* instance = getInstance();
// use instance as you need to get the appropriate result
}
So you enforce usage like this:
SomeSingleton::foo();
Some might even consider it more comfortable to use than
SomeSingleton::getInstance().foo();
By the way: This aproach makes it possible to protect you from race conditions, too, if multi-threading is or gets an issue:
class SomeSingleton
{
public:
static void foo();
private:
static std::mutex mutex; // <- add a mutex!
static SomeSingleton* getInstance();
static void exchange();
};
void SomeSingleton::foo()
{
// this must be added whenever the singleton is used...
std::lock_guard<std::mutex> guard(mutex);
SomeSingleton* instance = getInstance();
// use instance as you need to get the appropriate result
}
void SomeSingleton::exchange()
{
// ... or the singleton instance is re-asigned
std::lock_guard<std::mutex> guard(mutex);
SomeSingleton* newInstance = new SomeSingleton();
delete instance;
instance = newInstance;
}
My solution is a wrapper with overloaded -> operator like in smart pointers which calls getInstance() inside:
class Singleton {
friend SingletonWrapper;
private:
static Singleton * getInstance() {...}
public:
void foo() {}
};
class SingletonWrapper {
public:
Singleton * operator->() {
return Singleton::getInstance();
}
};
int main() {
SingletonWrapper w;
w->foo();
}
First of all I wouldn't suggest using pointers for singletons. This ("Meyer Singleton") is a much better approach.
static SingletonDatabase &get() {
static SingletonDatabase db;
return db;
}
Also storing the singleton is kind of a bad idea, as with the storing you validate the initial idea / purpose behind the singleton: You are making copies, thus the singleton is not the "sole" instance of the class.
Anyway a great solution to your problem would be to use some kind of signal/slot system. (Qt / Boost library) Upon change you can emit the singal, which is then "caught" by all instances and the actualize the values.
Boost Signals / Slots
Qt Signals Slots
I Hope this helps :)
Use volatile to declare the singleton variable. This will force the compiler to always check for it
class Singleton
{
private:
static volatile Singleton* instance;
private:
Singleton();
public:
static volatile Singleton* getInstance();
};

C++ singleton in constructor

Is this possible?
class A {
static A *instance = NULL;
public:
A () {
if (instance) {
this = instance;
} else {
instance = this;
}
}
}
Does it have leak memory?
Do I need to oveload new operator?
No. Overlooking your compiler errors, your class won't work.
#Galik has provided invaluable sources for how you'd actually want to construct a singleton. But let's look at yours.
class A {
static A *instance = NULL; // NULL isn't even a thing, but assuming you mean nullptr you can't assign a static like this
public:
A () {
if (instance) {
this = instance; // this can't be assigned
} else {
instance = this; // this is correct
}
}
};
Which would give you the following:
class A {
static A *instance;
public:
A () {
// if there's no instance, this is the one we'll use
if (!instance) {
instance = this;
}
}
};
A* A::instance = nullptr;
Which doesn't stop you from constructing more than one anyway.
Not possible. If the constructor is exposed and called, a new object of A is inevitably created. The most elegant and widely used implementations of C++ singleton classes use static methods to return the single static instance, while hiding (e.g. make private accessible) the constructor.
Here's an example:
class A {
private:
static A *instance_; // use nullptr since C++11
A() {}
public:
static A& instance() {
if (!instance_)
instance_ = new A();
return *instance_;
}
};
A* A::instance_ = nullptr;
You cannot assign a value for this

C++ Non-destructible classes

Is there any way in C++ to create class within a function, and then prevent it from destructing?
like
class someclass {
public:
int x;
someclass() { x = 0; };
}
someclass::x;
and then somewhere
someclass * somefunction()
{
someclass somecl ();
return &somecl;
}
So we call function 'somefunction' and get pointer to class for later using. I need it to exist as long as program runs/it destructed by other function. Is there any way to do it without storing it inside arrays or vectors?
I'm not sure if what you're looking for is a way to define an object once and only once, returning a pointer to the same object each time, or to create a factory function that returns the a newly constructed object each time. If it's the second, look at previous answers. If it's the first, check out static variables. As an example, you could write
someclass * somefunction()
{
static someclass somecl ();
return &somecl;
}
This ensures that somecl is only defined once, when the function is initially run and that it will be alive until your program exits. (For a more precise description of the order of cleanup for static variables, see here.)
Yes, you have to allocate the memory on the heap and then delete the memory when you are done.
someclass * somefunction()
{
return new someclass();
}
int main()
{
someclass * myclass = somefunction();
// do stuff with myclass
delete myclass;
return 0;
}
someclass * somefunction()
{
return new somecl ();
}
You were very close :)
You could create it on the heap rather than the stack:
someclass * somefunction()
{
return new someclass();
}
You may also want to consider returning it in a smart pointer, to explicitly transfer ownership and control its lifetime.
I'm not exactly sure what you are driving at, I can imagine two different use cases where you would want to make a class indestructible.
Case 1: Singleton
The idiomatic way to do this, is to use a static instance of the class that's declared within an accessor function:
class Foo {
public:
static Foo& globalFoo();
private:
Foo() {};
~Foo() {};
};
Foo& Foo::globalFoo() {
static Foo myFoo;
return myFoo;
}
int main() {
Foo& myFoo = Foo::globalFoo();
}
That way, it is impossible for other code to either construct or destruct any instance of Foo, it can only use the one instance that's provided by the globalFoo() function.
Case 2: Wrapped allocation/deallocation
If you just want to force allocation/deallocation to happen via certain static functions, you only need to make both the constructor and the destructor private (just as in the singleton case), and add static functions to the interface for allocation/deallocation:
class Foo {
public:
static Foo* makeFoo();
static void destroyFoo(Foo* aFoo);
private:
Foo() {};
~Foo() {};
};
Foo* Foo::makeFoo() {
return new Foo();
}
void Foo::destroyFoo(Foo* aFoo) {
delete aFoo;
}
int main() {
Foo* myFoo = Foo::makeFoo();
Foo::destroyFoo(myFoo);
}