Most Efficient Way to Use Singleton Classes - c++

In C++, I use a singleton class and refer to the only instance in another class. I'm wondering what is the most efficient way to access this instance since it is a large data structure. I considered these things.
Getting a reference from the singleton class, other than passing the data structure by value
Using a global instance in my second class which uses the singleton class:
Singleton* singleInstance;
SingletonUser::SingletonUser ()
{
singleInstance = Singleton::getInstance(); //passes the single instance by reference, then it will be used in the class wherever needed
}
Doing the same thing inside a function of the second class so that I get a reference to the singleton class's instance when I want it (Need to access it several times in several functions).
I'm not sure which practice is the best one. Can someone explain, and if there is a more efficient way, explain that too?
Thanks!

If you're passing your singleton instance by value, then it's not really a singleton, is it?
Simply return a reference (or a pointer) to the instance whenever you need to access it (#1). Caching the reference once for each client is only going to add complexity and almost certainly won't be any faster.
I'm not sure what the difference is between #1 and #3, besides added complexity. Both use a function to access the singleton instance via a reference/pointer.

Firstly in C++ avoid pointers when possible, instead pass by reference:
Singleton& Singleton::getInstance() {
return *singleton;
}
Then in the code:
Singleton& st = Singleton::getInstance();
st.someFunction();

Your option #3 is most preferable. Try to not cache references unnecessarily - those cached references tend to be a maintenance burden as time goes on.
And just in general, try avoid the singleton pattern. In C++, a global function (non-member) is just as good and allows the design to evolve.

Related

C++ Singletons: how good is this solution? Advantages/disadvantages, alternatives

I am working on a C++ project having multiple classes that must be singletons, with dependencies between them (order of initialization matters).
I have come up with this solution:
All classes which I want to be singletons have protected constructors, e.g.:
class MySingleton1
{
protected:
MySingleton1();
}
Have a source file singleton_factory.cpp containing an instantiated class Singletons which derives from all classes which I want to be singletons, like this:
#include "MySingleton1.hpp"
#include "MySingleton2.hpp"
class Singletons : public MySingleton1, public MySingleton2 {}
static Singletons s_singletons;
Still in singleton_factory.cpp, for every singleton type, also implement a specialization of a getSingleton function:
template<>
MySingleton1& getSingleton()
{
return s_singletons;
}
template<>
MySingleton2& getSingleton()
{
return s_singletons;
}
The specializations of getSingleton will be "hid" under the generic templated variant, in singleton_factory.hpp:
template <class TSingleton>
TSingleton& getSingleton();
Advantages:
Low-coupling:
Singleton classes don't need to be "aware" of the Singletons class, the only need to hide their constructor under a protected qualifier (and that is not even mandatory, only good practice). The only code actually aware of the Singletons class is singleton_factory.cpp
Skinny dependencies for concrete instance: code that wants to use a singleton of type T only needs to include the header of type T and the skinny singleton_factory.hpp
Order of initialization can be controlled by changing the order of inheritance of the Singletons class
No lazy initialization => thread-safe?
getSingleton() is fast, no dynamic_cast, no reinterpret_cast
Disadvantages:
Every time a new singleton type appears, a getSingleton specialization, doing the same - i.e. "return s_singletons;" must be added to singleton_factory.cpp
So, as far as I can see, this is actually fairly good so I'm thinking to leave it like this, but I'm asking for your feedback (what better place to do that than the programming community?).
What extra advantages/disadvantages do you see with this solution?
What alternatives do you suggest?
This forces centralization of Singletons, which can mess up dependencies in more complex projects. The library that has singleton.cpp must depend on everything needed for every singleton. At the same time, anyone who uses a singleton must depend on the singleton.cpp library.
Basically your code could only work in a monolithic non-modular project. Scaling this to multiple dynamic libraries is next to impossible.
Your order of initialization must be maintained manually.
The static global variable's construction point is unsequenced with everything prior to the first expression in main.
A decent solution I've used is to create a dynamic library that holds the singleton memory.
To be a singleton, you inherit from a CRTP helper, which provides a ::Instance() inline method. People wanting the singleton use ::Instance().
::Instance() creates a static local variable lifetime token. It then attempts to get storage for the singleton from the primary DLL; if the object is already created, it simply casts the storage into the object type, and increases its reference count.
If not, it creates new storage and constructs the object in it.
At the destruction of the static local variable lifetime token, it reduces the reference count. If that reference count hits 0, it destroys it locally in the current dynamic library.
The lifetime of the singleton is now the union of the lifetime of the ::Instance() created variables. Destruction occurs in non-type-erased code, so we don't have to worry about the DLL with the code being unloaded. Storage is central. The DLL that stores the storage has to be lower level than every user of the Singleton system, but it in turn has no dependencies, so that isn't a pain.
This is far from perfect; singletons and lifetime are a constant problem, because clean program shutdown is hard and made harder by singleton's existence. But it has worked so far in a reasonably large project.
Can you use dependency injection in your case? i.e. have some serialized code create an instance of each class and pass a reference to the instance(s) into the constructors of any other instances that need access to them? This might simplify your design, if applicable. Ideally you could pass a separate, newly-created instance into each constructor to further reduce coupling but it seems you need to share state. In any case, perhaps it helps.

perfect singleton design pattern

recently I faced an question, design perfect single tone pattern.
I have designed by using one static instance and one static function returns that instance as below.
ST* ST::instance = NULL;
ST* ST::getInstance()
{
mutex.lock();
if(!instance)
instance = new ST();
mutex.lock();
return instance ;
}
The he asked me to write without using mutex (write perfect singleton without using any synchronization mechanism), then I have changed as below.
ST* ST::instance = new ST();
ST* ST::getInstance()
{
return instance ;
}
Is it a perfect design ?? what does he mean of perfect design of single tone pattern ???
What might be his expectation of design ??
Thanks in advance.
There is no perfect singleton. In fact, it's open to some question whether there's any singleton that's worth anything at all.
That said, in C++ the Meyers Singleton is usually the one that's least problematic. The core of it looks roughly like this:
static T &get_instance() {
static T t;
return t;
}
So the basic idea is to define a single instance of the target type as a static, local to a static member function. That static member function returns a reference to that object. All singleton's constructors are private, so only member functions can use them to create (or destroy) objects of that class. In effect, this means only the one static member function can ever create an instance, and it only creates the one static instance, so all use is of that one instance.
Of course, if you want to badly enough, you can return a pointer instead of a reference, but that's rarely a good idea (probably not a good candidate for "perfect").

Is it right way to create sinlgeton class by weak_ptr

I create a parent class to handle singleton pattern with smart pointer:
.h file:
template<class singleType>
class Singleton
{
public:
static std::shared_ptr<singleType> GetInstance();
private:
static std::weak_ptr<singleType> m_singleObject;
};
.cpp file:
template<class singleType>
std::shared_ptr<singleType> Singleton<singleType>::GetInstance()
{
auto shareObject = m_singleObject.Lock();
if (!shareObject)
{
shareObject.reset(new singleType);
m_singleObject = shareObject;
}
return shareObject;
}
Not sure it is the right way to use smart pointer?
Any idea?
Many Thanks
The pros and cons of this implementation are already discussed. But there are a bunch of bugs:
1) As this is a template you have to move your implementation into the header or the linker cannot find it.
2) The .lock() function of the weak_ptr is not in capitals.
3) Don't forget to instantiate
template<class singleType>
std::weak_ptr<singleType> Singleton<singleType>::m_singleObject;
4) Better use shareObject = std::make_shared<singleType>(singleType()); instead of the new: http://herbsutter.com/gotw/_103/
5) As Konrad mentioned: it's not thread-safe.
I did some research so now I'll post an answer.
The code all looks like it should work and is a correct usage of smart pointers. The only question is how exactly you want the singleton to behave. This should behave like a textbook singleton EXCEPT for the behavior that if nothing currently has a pointer to the singleton, it will delete itself. This behavior is something that really depends on the implementation of your program. If you want the singelton to only exist when it is in use, then I'd say go for it.
I would just avoid creating and destroying the singelton too often especially if the construction and deconstruction are particularly intensive. If it is constantly getting created and deleted then you are probably better off with a more standard singleton implementation. The standard singleton behavior tends to be that a singleton is only created once during the duration of the program running and is never deleted.
I think this is a clever implementation given you have a use for it and I might have to borrow the idea.
Your code isn’t thread safe.
The name lock may suggest that concurrent access is blocked but in fact there’s no such guarantee: when multiple threads concurrently call your GetInstance function you will get several instances instead of guaranteeing a single one.
You need to create an explicit lock for the whole duration of the GetInstance function’s lifetime. Note that this is of course not very efficient.
To the best of my knowledge this should be fine. You'll avoid out of order destruction issues, but it could be a problem to create new instances after your initial instance is created. This singleton will have only one instance alive at any time, but over the course of the program running more than one instance may have been alive overall.
This destruction and recreation may also be unwanted in terms of performance, not only in side-effects.

singleton and classic constructor

This question is fairly fundamental.I gave a simple and straighfoward test on my cygwin:
class Example {
public:
Example(){ cout<<"dude..."<<endl; }
~Example(){ cout<<"see ya"<<endl; }
public:
static Example *GetInstance(){
if(m_instance==NULL){
m_instance = new Example();
cout<<"watch out bro"<<endl;
}
return m_instance;
}
public:
void exp(){cout<<"greetings"<<endl;}
private:
static Example *m_instance;
};
int main(){
Example a;
return 0;
}
Obviously,the output is:
dude...
greetings
see ya
Technically singleton and typical constructor are pretty much different stories in c++ programming since singleton puts constructor as private while typical way is opposite.In my recent internship experiences I have noticed that most coders implement APIs in this manner.
I just wonder if that is the case or unnecessary when both class construction approaches exist in parallel.
UPDATE
Is constructor & singleton existing in one program practically nonsense cuz singleton stuff in this scope would become useless codes like unhazardous trash?
SUMMARY
This is quite a nonsense question...
and what's more,thanks to all of you brilliants
constructor and singleton design pattern are "mutually exclusive" and in terms of vulnerbility,it is the same story as global variables kill our debug time...
By making the constructor of Example public, you allow users of your class to create an instance directly. If your design requires only one instance of your singleton then this allows users to inadvertently subvert this requirement. If you had made the constructor private then calling GetInstance() would be the only way to create an Example object, thus enforcing the requirement to allow only one instance to be created.
Note that static objects are destroyed in reverse order to which they were created. This causes a problem if the objects refer to each other. This is a trap for people maintaining your code, and if you have more than a few such objects this quickly becomes unmanageable.
Many developers consider singletons to be a Bad Thing much like global variables:
https://sites.google.com/site/steveyegge2/singleton-considered-stupid
When using the Singleton design pattern you always should make the constructors (copy constructor as well) and the operator = as private to ensure there will be only one instance of the given class. Otherwise the Singleton pattern wouldn't make much sense.
I think that you missed the whole concept of singleton. Singleton means that there is only one instance, but public constructor can construct lot of objects.
I think that example is broken. It allows user to create multiple "singletons" and then obviously they are no singletons.
In singleton constructor has to be private.
Just making the constructor private doesn't make the class Singleton. For that you have to make sure no other instances are present in the memory before you call the constructor. Even though the constructor is private any number of instances of the class can be created from static class members
Singleton is a technique to make sure there's only one instance to a class created. By exposing a public constructor you're obviously opening the door for multiple instances thus your class may not be called a singleton.
However it still has a static GetInstance() method that's somewhat expected as a singleton interface, and that makes it confusing to who didn't write the code (or even to the author some time later).

C++ singleton vs. global static object

A friend of mine today asked me why should he prefer use of singleton over global static object?
The way I started it to explain was that the singleton can have state vs. static global object won't...but then I wasn't sure..because this in C++.. (I was coming from C#)
What are the advantages one over the other? (in C++)
Actually, in C++ preferred way is local static object.
Printer & thePrinter() {
static Printer printer;
return printer;
}
This is technically a singleton though, this function can even be a static method of a class. So it guaranties to be constructed before used unlike with global static objects, that can be created in any order, making it possible to fail unconsistently when one global object uses another, quite a common scenario.
What makes it better than common way of doing singletons with creating new instance by calling new is that object destructor will be called at the end of a program. It won't happen with dynamically allocated singleton.
Another positive side is there's no way to access singleton before it gets created, even from other static methods or from subclasses. Saves you some debugging time.
In C++, the order of instantiation of static objects in different compilation units is undefined. Thus it's possible for one global to reference another which is not constructed, blowing up your program. The singleton pattern removes this problem by tying construction to a static member function or free function.
There's a decent summary here.
A friend of mine today asked me why should he prefer use of singleton over global static object? The way I started it to explain was that the singleton can have state vs. static global object won't...but then I wasn't sure..because this in C++.. (I was coming from C#)
A static global object can have state in C# as well:
class myclass {
// can have state
// ...
public static myclass m = new myclass(); // globally accessible static instance, which can have state
}
What are the advantages one over the other? (in C++)
A singleton cripples your code, a global static instance does not.
There are countless questions on SO about the problems with singletons already. Here's one, and another, or another.
In short, a singleton gives you two things:
a globally accessible object, and
a guarantee that only one instance can be created.
If we want just the first point, we should create a globally accessible object.
And why would we ever want the second? We don't know in advance how our code may be used in the future, so why nail it down and remove what may be useful functionality? We're usually wrong when we predict that "I'll only need one instance". And there's a big difference between "I'll only need one instance" (correct answer is then to create one instance), and "the application can't under any circumstances run correctly if more than one instance is created. It will crash, format the user's harddrive and publish sensitive data on the internet" (the answer here is then: Most likely your app is broken, but if it isn't, then yes, a singleton is what you need)
Reason 1:
Singletons are easy to make so they are lazy build.
While you can do this with globals it take extra work by the developer. So by default globals are always initialized (apart from some special rules with namespaces).
So if your object is large and/or expensive to build you may not want to build it unless you really have to use it.
Reason 2:
Order of initialization (and destruction) problem.
GlobalRes& getGlobalRes()
{
static GlobalRes instance; // Lazily initialized.
return instance;
}
GlobalResTwo& getGlobalResTwo()
{
static GlobalResTwo instance; // Lazy again.
return instance;
}
// Order of destruction problem.
// The destructor of this object uses another global object so
// the order of destruction is important.
class GlobalResTwo
{
public:
GlobalResTwo()
{
getGlobalRes();
// At this point globalRes is fully initialized.
// Because it is fully initialized before this object it will be destroyed
// after this object is destroyed (Guaranteed)
}
~GlobalResTwo()
{
// It is safe to use globalRes because we know it will not be destroyed
// before this object.
getGlobalRes().doStuff();
}
};
Another benefit of the Singleton over the global static object is that because the constructor is private, there is a very clear, compiler enforced directive saying "There can only be one".
In comparison, with the global static object, there will be nothing stopping a developer writing code that creates an additional instance of this object.
The benefit of the extra constraint is that you have a guarantee as to how the object will be used.
Using Singleton("construct on first use") idiom, you can avoid static initialization order fiasco
In C++, there's not a huge amount of difference between the two in terms of actual usefulness. A global object can of course maintain its own state (possibly with other global variables, though I don't recommend it). If you're going to use a global or a singleton (and there are many reasons not to), the biggest reason to use a singleton over a global object is that with a singleton, you can have dynamic polymorphism by having several classes inheriting from a singleton base class.
OK, there are two reasons to go with a singleton really. One is the static order thing everyone's talking about.
The other is to prevent someone from doing something like this when using your code:
CoolThing blah;
gs_coolGlobalStaticThing = blah;
or, even worse:
gs_coolGlobalStaticThing = {};
The encapsulation aspect will protect your instance from idiots and malicious jerks.