[gameprogrammer] Re: problem with singleton
- From: "Dave Slutzkin" <daveslutzkin@xxxxxxxxxxx>
- To: gameprogrammer@xxxxxxxxxxxxx
- Date: Wed, 16 Jun 2004 14:16:45 +1000
On Mon, 14 Jun 2004 11:05:05 -0400, "Roger D. Vargas"
<roger@xxxxxxxxxxx> said:
> I tried to implement the cache class as a singleton. Here is the code:
>
> class TVTextures {
> public:
> static TVTextures getCache() { return _instance; };
> ~TVTextures();
> protected:
> TVTextures();
> static TVTextures _instance;
> };
>
> But whenever I try to use the class like this:
> TVTextures::getCache().AddImage(STSTR,driver->getTexture("strength_i.jpg"));
> i got an error a linking error: undefined reference to
> `tower::TVTextures::_instance'
I can't see if this has already been answered, but all you have at the
moment is the declaration of the static member - that is, you're saying
that the name exists. You also need a definition somewhere in your
code, so that the compiler can allocate memory for the object and the
linker can find where that memory is. In order to avoid having the
object multiply-defined, this definition should be in a source file,
most likely TVTextures.c, or whatever your naming convention is. So the
line is:
TVTextures TVTextures::_instance;
Although... There is a slight problem with implementing Singleton this
way, which you may or may not run into. (If you don't, don't worry
about it.) This static object has to be initialized at some point, and
the compiler will generate the code to initialize it at a random time
(or at least, one which you have no control over). If you try to access
it before it's initialized (like from the constructor of another static
object), you run into problems because it's not created yet. So there
are multiple other and probably better ways to do it, as mentioned in
detail in Alexandrescu's Modern C++ Design book. This is a big, complex
book though.
Briefly, the other way I usually do it is:
static TVTextures::singleton()
{
static TVTextures sSingleton;
return sSingleton;
}
This ensures that as soon as the function is called, this object is
allocated so it always exists when it's used.
Hope that helps,
Dave.
--
Dave Slutzkin
Melbourne, Australia
daveslutzkin@xxxxxxxxxxx
---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html
- Follow-Ups:
- [gameprogrammer] Re: problem with singleton
- From: Roger D. Vargas
- References:
- [gameprogrammer] problem with singleton
- From: Roger D. Vargas
Other related posts:
- » [gameprogrammer] problem with singleton
- » [gameprogrammer] Re: problem with singleton
- » [gameprogrammer] Re: problem with singleton
- » [gameprogrammer] Re: problem with singleton
- » [gameprogrammer] Re: problem with singleton
- [gameprogrammer] Re: problem with singleton
- From: Roger D. Vargas
- [gameprogrammer] problem with singleton
- From: Roger D. Vargas