Reputation: 91
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 to
Singleton::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
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
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