Izza
Izza

Reputation: 2419

Most Efficient Way to Use Singleton Classes

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.

  1. Getting a reference from the singleton class, other than passing the data structure by value
  2. 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
    }
    
  3. 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

Answers (3)

David C. Bishop
David C. Bishop

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

mcmcc
mcmcc

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

Cameron
Cameron

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

Related Questions