I have a question with singlton.
Where should I declare the static member of the singleton class?
why not working like this
class singleton{
private:
static singleton & m_singleton;
public:
static singleton& get_instance{
return m_singleton;
}
}
but I have to be like this
class singleton{
public:
static singleton& get_instance{
static singleton & m_singleton;
return m_singleton;
}
}
What's the differnece?
I know there is another way to use pointer, but now I am only talking about the case to use an object.
Also another questions, what's the pros/cons to use pointer and reference for singleton ?
Thanks so much!
In the first case, the singleton is constructed (constructor called) when the program initializes, before main() is called. In this case you will also need to define the static variable somewhere in your cpp file.
In the second case the singleton is constructed when the function is first called. Mind you that this implementation is not thread safe since static variable initialization in functions is not thread safe. If two threads call this function for what appears to be the first time, there is a small chance you'll end up with two singletons.
Also notice you have a bug in the second one. You cannot define a reference without an initalization. This
static SomeClass &var;
Does not compile. You need to remove the reference to create an actual instance of the class, not a reference, and then return a reference to it.
If in the second example you define the static variable as a pointer you can avoid the threading problem I mentioned by carefully initializing the pointer. Read more about it in this class article (that talks about Java but the core issue is the same)
Related
If I return a reference to my instance of MySingleton from GetInstance() instead of the pointer in my code below, it will be valid, but is using the pointer in this way also valid?
I assume my pointer will only get initialized once because it is static, but not not sure.
I know the correct way by using raw pointers within a singleton is to check if the pointer is first null before assigning it, but wondering if the below code is also valid. Thanks
class MySingleton
{
public:
static MySingleton* GetInstance()
{
static MySingleton* inst = new MySingleton();
return inst;
}
private:
MySingleton(){};
};
EDIT: I haven't seen this exact implementation for a Singleton implemented in the reported duplicate question
Your implementation is acceptable (as is any other) as long as any one of the following holds:
Your singleton does not acquire any external resources (anything: file handles, network connections, shared memory) for longer than a single exception-safe method invocation.
The last user of your singleton deletes the instance manually.
Otherwise something serious can leak.
You can wrap the instance in something automatic, like std::unique_ptr, but this immediately casts usual singleton lifetime issues.
See std::call_once and std::once_flag for implementing singleton pattern. Your implementation will lead to troubles in a multithreaded environment.
Most of is seem to have missed the simplest possible form of C++ singleton AKA Scott Meyer's Singleton. Ever since C++11 it has become as easy as a pie:
class singleton{
singleton();
singleton(singleton&&)=delete;
singleton(singleton const&)=delete;
void operator(singleton&&)=delete;
void operator(singleton const&)=delete;
//...
public:
static auto& singleton::instance(){
static singleton val{};
return val;
}
};
No need for complex code.
I will demonstrate my question using a Singleton pattern but it is a broader question. Please spare me the "Singletons are evil" lectures.
Version 1 of Singleton
class Singleton
{
public:
static Singleton& getInstance()
{
static Singleton instance; // This becomes a class member in Ver.2
return instance;
}
private:
// Constructor, forbid copy and assign operations etc...
}
Version 2 of Singleton
class Singleton
{
public:
static Singleton& getInstance()
{
return instance;
}
private:
static Singleton instance; // I'm here now!
// Constructor, forbid copy and assign operations etc...
}
I will now explain what I think will be the difference is between the two:
Version 1 instance will only be initialized once the flow of the program reaches the actual definition of instance (i.e some part of the program requests an instance using Singleton::getInstace()). Lazy instantiated in other words.
It will only be destroyed when the program terminates.
Version 2 instance will be initialized at the start of the program, before main() is called. Will also be destroyed only when the program terminates.
First of all, am I correct in the above assumptions?
Second, Is this behavior of initialization universal (say for global variables and functions)?
Last, Are there any other nuances I should be alerted about concerning this?
Thanks!
You are correct.
You should also notice that the 2nd version does not guarantee when will the object be created, only that it will be before the main function is called.
This will cause problems if that singleton depends on other singletons and etc
That is, the first version will give you greater control over your code, initialization order and of course - less bugs :)
In C++, can all the members in a singleton be static, or as much as possible? My thought is, there is only one instance globally anyway.
While searching I did find a lot of discussions on static class in C#, but not familiar about that. Would like to learn about it too.
Whatever thought you have, please comment.
With a static singleton you can't control when the single will be allocated and constructed. This puts you at the mercy of the c++ order of construction rules for static variables, so if you happen to call this single during the construction of another static variable, the single may not exist yet.
If you have no intentions of ever calling the singleton from the constructor of another static variable, and do not wish to delay construction for any reason, using a static variable for singleton is fine.
See Static variables initialisation order for more info.
The singleton pattern, as you probably know, contains a static method Instance which will create the instance if and only if it exists and return that instance. There is no reason that other or all methods of the singleton could not be static. However, given that there is ever only one instance of the class i'm not sure it makes sense to make everything else static. Does that make sense?
Much of the point of a singleton is to have some control over when it's created.
With static data members you forfeit that control, for those members.
So it's less than smart doing that.
That said, singletons are generally Evil™ with many of the same problems as pure global variables, including the tendency to serve as an uncontrollable communications hub that propagates various unpredictable effects rather willy-nilly from unpredictable places to other unpredictable and largely unknown places, at unpredictable times.
So it's a good idea to think hard about it: is a singleton really the answer, or could it, in the case at hand, be just a way to compound the problem it was meant to solve?
To answer your question: The case you're suggesting is more like a 'static class' in C# and C++ doesn't have a concept of 'static class'.
Usually in a C++ singleton class, the only static data member is the singleton instance itself. This can either be a pointer to the singleton class or a simply an instance.
There are two ways to create a singleton class without the singleton instance being a pointer.
1)
class MySingletonClass
{
public:
static MySingletonClass& getInstance()
{
static MySingletonClass instance;
return instance;
}
// non-static functions
private:
// non-static data-members
};
2)
class MySingletonClass
{
public:
static MySingletonClass& getInstance()
{
return sInstance;
}
// non-static functions
private:
static MySingletonClass sInstance;
// non-static data-members
};
// In CPP file
MySingletonClass MySingletonClass::sInstance;
This implementation is not thread-safe, not predictable in terms of when it gets constructed or when it gets destroyed. If this instances depends on another singleton to destroy itself, it can cause unidentifiable errors when exiting your application.
The one with the pointer looks something like this:
class MySingletonClass
{
public:
static MySingletonClass& getInstance()
{
return *sInstance;
}
static MySingletonClass* getInstancePointer()
{
return sInstance;
}
MySingletonClass()
{
if (sInstance) {
throw std::runtime_error("An instance of this class already exists");
}
sInstance = this;
}
// non-static functions
private:
static MySingletonClass* sInstance;
// non-static data-members
};
Inialization of such a singleton class would usually happen during application initialization:
void MyApp::init()
{
// Some stuff to be initalized before MySingletonClass gets initialized.
MySingletonClass* mySingleton = new MySingletonClass(); // Initalization is determined.
// Rest of initialization
}
void MyApp::update()
{
// Stuff to update before MySingletonClass
MySingletonClass::getInstance().update(); // <-- that's how you access non-static functions.
// Stuff to update after MySingletonClass has been updated.
}
void MyApp::destroy()
{
// Destroy stuff created after singleton creation
delete MySingletonClass::getInstancePointer();
// Destroy stuff created before singleton creation
}
Although the initalization and destruction of singleton is controlled in this scenario, singletons don't play well in a multi-threaded application. I hope this clears your doubts.
the short answer: yes! sure! C++ is flexible, and almost everything is possible (especially such a simple things).
the detailed answer depends on your use cases.
how may other statics/globals depends on your signleton
when the very first access to your singleton going to happen (probably before main?)
lot of other things you have to take in account (most of them related to interaction of your singleton w/ other entities)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is so bad about singletons?
Singleton pattern in C++
I want to create a singleton class. For that, I created a class with all its member and methods as static. Something like this.
class a
{
static int a;
static GetA();
}
Now all the classes who want to use my singleton class cannot create any object for my class and also will get same value. I just want to know whether this implementation will solve all the purpose and fulfill all criteria for creating a singleton class.
I prefer:
GlobalObjectMgr& GlobalObjectMgr::instance()
{
static GlobalObjectMgr objMgr;
return objMgr;
}
There is no class member variable required and it is created only when needed.
The conventional Singleton (anti-)pattern isn't a collection of static variables; rather, it is an object with non-static members, of which only one instance can exist.
In C++, this allows you to avoid the biggest problem with static variables: the "initialisation order fiasco". Because the initialisation order is unspecified for static variables in different translation units, there's a danger that the constructor of one might try to access another before it is initialised, giving undefined behaviour. However, it introduces other problems (a similar "destruction order fiasco", and thread safety issues in older compilers), so it's still something to avoid.
If you want a collection of static variables and functions, then put them in a namespace rather than a class:
namespace stuff {
int a;
void do_something();
}
If you think you want a singleton, then think again; you're generally better avoiding globally accessible objects altogether. If you still want one, then you would make a class with a private constructor, and a public accessor that returns a reference to the single instance, along the lines of:
class singleton {
public:
singleton & get() {
static singleton instance;
return instance;
}
int a;
void do_something();
private:
singleton() {}
~singleton() {}
singleton(singleton const &) = delete;
};
When I look for informations about the singleton pattern for C++, I always find examples like this:
class Singleton
{
public:
~Singleton() {
}
static Singleton* getInstance()
{
if(instance == NULL) {
instance = new Singleton();
}
return instance;
}
protected:
Singleton() {
}
private:
static Singleton* instance;
};
Singleton* Singleton::instance = NULL;
But this kind of singleton also seems to work as well:
class Singleton
{
public:
~Singleton() {
}
static Singleton* getInstance()
{
return &instance;
}
protected:
Singleton() {
}
private:
static Singleton instance;
};
Singleton Singleton::instance;
I guess that the second singleton is instantiated at the beginning of the program, unlike the first, but is it the only difference?
Why do we find mainly the first?
http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14
The static initialization order fiasco is a very subtle and commonly
misunderstood aspect of C++. Unfortunately it's very hard to detect —
the errors often occur before main() begins.
In short, suppose you have two static objects x and y which exist in
separate source files, say x.cpp and y.cpp. Suppose further that the
initialization for the y object (typically the y object's constructor)
calls some method on the x object.
That's it. It's that simple.
The tragedy is that you have a 50%-50% chance of dying. If the
compilation unit for x.cpp happens to get initialized first, all is
well. But if the compilation unit for y.cpp get initialized first,
then y's initialization will get run before x's initialization, and
you're toast. E.g., y's constructor could call a method on the x
object, yet the x object hasn't yet been constructed.
The first method you listed avoids this problem completely. It's called the "construct on first use idiom"
The downside of this approach is that the object is never destructed.
There is another technique that answers this concern, but it needs to
be used with care since it creates the possibility of another (equally
nasty) problem.
Note: The static initialization order fiasco can also, in some cases,
apply to built-in/intrinsic types.
The first one allows you to delete the instance while the second one does not. But please be aware that your first example is not thread safe
It's commonly known as the static initialization order fiasco. In summary, static instances at file scope are not necessarily initialized before explicit function calls that create one as in your first example.
The singleton patterns is commonly considered Bad Practice, so empirical evidence (what you "see most") is of little value in this case.
The first version uses dynamic allocation, while the second one uses static allocation. That is, the second allocation cannot fail, while the first one could possibly throw an exception.
There are pros and cons to both versions, but generally you should try for a different design that doesn't require singletons at all.
The first one is also "lazy" - it will be created only if and when it is needed. If your Singleton is expensive, this is probably what you want.
If your Singleton is cheap and you can deal with undefined order of static initialization (and you don't use it before main()), you might as well go for the second solution.