0

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;
}

2 Answers2

1

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.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

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
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • i dont understand this. I read the concept of singleton, saw some examples and trying to implement it. what does meyers do thats fixing the problem im having ? – Kim Kardashian Oct 21 '16 at 18:04
  • This code is simpler than yours and avoids the static initialization order fiasco https://isocpp.org/wiki/faq/ctors#static-init-order – drescherjm Oct 21 '16 at 18:09