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.