Archived

This topic is now archived and is closed to further replies.

fallenang3l

Enginuity part 2 singleton

Recommended Posts

fallenang3l    144
Here''s the page I''m referring to: http://www.gamedev.net/reference/programming/features/enginuity2/page5.asp (about half-way down). I understand the concept of singletons and I can model my own but I don''t understand one thing about this one. Why bother creating an offset variable and do all that whack casting if the result is always 0. Why not just ms_singleton = (T*)this;?

Share this post


Link to post
Share on other sites
jamessharpe    497
It''s to do with multiple inheritance.
Consider class Y derived from singleton and X: it could be coded either:

class Y: public X, public Singleton

or
class Y: public Singleton, public X

This would result in the memory being laid out as:

XXX S S YYYY

or

S S XXX YYY

So when you return the pointer to the singleton object in the second case you will return the right address, but in the first case, you will be returning a pointer to half way through the object.

Share this post


Link to post
Share on other sites
biovenger    122
Isn't it just possible to instead to make a class a singleton by not inheritance, but ownership? Imagine this...


// singleton.h

template <typename T> class Singleton
{
private:
static T *self;

public:
Singleton() { if(!self) self = new T; }

GetInterface() { return self; }
};

template <typename T>
bool Singleton<T>::self = NULL;

// Other source file with wanted singleton class

class foobar
{
// Important, singleton class must be able to instantiate

friend class Singleton<foobar>;

private:
// Variables and whatever you want

//...


// Important part, the singleton

Singleton<foobar> self;

// Also important, private ctors for impossible instantation

foobar() { /*stuff...*/ }
foobar(const foobar &cpy) { /*stuff...*/ }
foobar & operator=(const foobar &cpy) { /*stuff...*/ }

public:
// The method that does it all

static foobar * GetInterface() { return self.GetInterface(); }

// More methods and variables

};

// Random cpp file


foobar *foo = foobar::GetInterface(); // Should be a singleton?



Alright, begin with the beating and tell me why the above code won't work, heh...

[edited by - biovenger on July 8, 2003 3:13:27 PM]

Share this post


Link to post
Share on other sites
fallenang3l    144
Out of curiosity, I've toyed with this code a little bit more and I've found out that by simply doing the following in the Singleton constructor suffices:
ms_singleton = static_cast<T*>(this); 


The address which the above produces is the same as with the code that manually does all the calculations, even if multiple inheritance is involved with the following case:
class Y: public X, public Singleton<Y> 


Or am I wrong because I'm failing to see something?


[edited by - fallenang3l on July 8, 2003 8:24:34 PM]

Share this post


Link to post
Share on other sites