Kim Kardashian
Kim Kardashian

Reputation: 91

Error in Singleton pattern implementation

I see errors like

src/singleton.cxx:16:error: invalid use of member 'Singleton::instance' in static member function src/singleton.cxx:28:error: from this location src/singleton.cxx:16:error: invalid use of member 'Singleton::instance' in static member function src/singleton.cxx:29:error: from this location src/singleton.cxx:16:error: invalid use of member 'Singleton::instance' in static member function src/singleton.cxx:31:error: from this location src/singleton.cxx: In function 'int main()':

Now after making changes I get the following errors

singleton-rhel6.3.o: In function Singleton::get_instance()': src/singleton.cxx:27: undefined reference toSingleton::instance'

#include <cstddef>

class Singleton {

private:
  Singleton();
  static Singleton * instance;
  int m_num;
  int incr_call();

public :
  static Singleton * get_instance();

};

Singleton * Singleton::get_instance() {
  if(instance == NULL)
    instance = new Singleton();
  return instance;
}

Singleton::Singleton():
  m_num(0)
{
}

int Singleton::incr_call() {
  return m_num++;
}

int main() {
  Singleton * s = Singleton::get_instance();
  return 0;
}

Upvotes: 0

Views: 227

Answers (2)

Jarod42
Jarod42

Reputation: 218098

If you have to use singleton, use Meyers' one:

class Singleton {
private:
    Singleton() = default;
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

public :
    static Singleton& get_instance()
    {
        static Singleton instance;
        return instance;
    }

// Extra stuff
};

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36503

instance should be static since you want to be able to call it in get_instance. Also, instance should be private:

class Singleton {

public :
  static Singleton * get_instance();


private:
  Singleton();
  static Singleton * instance;
  int m_num;
  int incr_call();

};
Singleton* Singleton::instance;

You should change your constructor too, to not initialize instance:

Singleton::Singleton():
  m_num(0)
{ }

Because instance is static default initialization is done and it will be NULL / nullptr.

Upvotes: 1

Related Questions