Re: Singleton Correct Usage
You do not show your Singleton class, but I assume that in it you
have something like:
Code:
class Gravity
{
// other stuff
static Gravity* m_instance; // declares a static variable
};
You declared a static class variable, but you still need to define it
Code:
Gravity* Gravity::m_instance= 0;
Re: Singleton Correct Usage
Re: Singleton Correct Usage
I don't understand. The pointer is set in the GetInstance() method (if it hasn't been already). Why do you set it to zero, and where?
Here is my singleton:
Code:
// ***** Gravity.h *****
class Gravity
{
public:
static Gravity* GetInstance();
~Gravity();
double GetGravity();
void SetGravity(double newVal);
protected:
Gravity();
Gravity(const Gravity& prm1);
Gravity& operator=(const Gravity& prm1);
private:
double m_gravity;
static Gravity* m_instance; // Defined in the source file
};
// ***** Gravity.cpp *****
Gravity::Gravity()
: m_gravity(-9.81)
{}
Gravity::~Gravity(){}
Gravity* Gravity::GetInstance()
{
if (!m_instance)
{
static Gravity instance;//m_instance = new Gravity();
m_instance = &instance;
}
return m_instance;
}
// Properties
double Gravity::GetGravity(){
return m_gravity;
}
void Gravity::SetGravity(SurfaceGravity newVal){
m_gravity = newVal;
}
Re: Singleton Correct Usage
Any static class member variable must to defined.
So in gravity.cpp ...
Code:
include "gravity.h"
Gravity* Gravity::m_instance= 0;
Re: Singleton Correct Usage
Thank you, that nailed it.
Just wondering, is there no way to set a static variable within the class itself?
Re: Singleton Correct Usage
you can initialize it within the class itself only if it is of const integral
or const enumeration type ... but it still must be defined.
Code:
struct S
{
static const int x = 10;
};
const int S::x; // still needed
Re: Singleton Correct Usage
Quote:
Originally Posted by Philip Nicoletti
you can initialize it within the class itself only if it is of const integral
or const enumeration type ... but it still must be defined.
Code:
struct S
{
static const int x = 10;
};
const int S::x; // still needed
While this is correct by specification, it may cause problems with certain compilers, if you try to take the address of "x".....
Re: Singleton Correct Usage
Thank you Philip and Wizard, that really clarified the correct implementation of static member variables for me.