Reputation: 2419
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.
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!
Upvotes: 1
Views: 1051
Reputation: 6615
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();
Upvotes: 2
Reputation: 842
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.
Upvotes: 1
Reputation: 98816
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.
Upvotes: 3