user2070245
user2070245

Reputation:

Return const reference to singleton

I am trying to implement a Singleton pattern with some pre-defined method declarations. I thoght it works but getting a second instance produces another instance.

I cannot change the method declarations or the member variables. I have build a little example:

#include <iostream>
#include <vector>

using namespace std;

class Singleton
{
  private:
    Singleton() {};

    vector<string> data;
    static Singleton *instance;

  public:
    static const Singleton &getInstance()
    {
      if(0 == instance) {
        instance = new Singleton;
      }
      return *instance;
    }

    void push(string &new_element)
    {
      data.push_back(new_element);
    }

    void print()
    {
      for(vector<string>::iterator it = data.begin(); it != data.end(); ++it) {
        cout << *it << endl;
      }
    }
};

Singleton *Singleton::instance = 0;

int main()
{
  Singleton a = Singleton::getInstance();
  Singleton b = Singleton::getInstance();

  string c1 = "Hello";
  string c2 = "World";

  a.push(c1);
  b.push(c2);

  a.print(); // prints only "hello"
}

My second attempt was to change a and b to a reference like this:

  Singleton &a = Singleton::getInstance();
  Singleton &b = Singleton::getInstance();

But this leads to another error:

singleton.cpp:40:45: error: invalid initialization of reference of type ‘Singleton&’ from expression of type ‘const Singleton’
singleton.cpp:41:45: error: invalid initialization of reference of type ‘Singleton&’ from expression of type ‘const Singleton’

Why does this happen? Can somebody explain, why new instances of Singleton are created?

I did search the web for answers, but nobody really used the Singleton pattern like I have to. (I'd change the inner structure if I could, but this is some kind of homework with given code.)

Upvotes: 0

Views: 663

Answers (2)

user634175
user634175

Reputation:

This code causes the Singleton instance to be copied:

Singleton a = Singleton::getInstance();

Changing the code to

const Singleton& a = Singleton::getInstance();

will fix the problem. You should make the copy constructor (and assignment operator) of Singleton private to disallow copying and assignment at compile time:

private:
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);

Upvotes: 2

eduffy
eduffy

Reputation: 40232

They need to be const references:

   const Singleton &a = Singleton::getInstance();

Upvotes: 0

Related Questions