I've done a quick google and board search, but didn't turn up any promising results. What I'm trying to do is write a simple class, encapsulating a pseudo-Singleton pointer:
Code:
class MySingleton
{
public:
class Inst
{
public:
Inst() {ptr = MySingleton::getInst();}
~Inst() {MySingleton::delRef(ptr);}
MySingleton* operator-> () {return ptr;}
protected:
MySingleton* ptr;
};
//some data members
protected:
MySingleton();
static MySingleton* ptr;
static int* refCount;
static MySingleton* getInst();
static void delRef(MySingleton*& ref);
friend class Inst;
};
Currently the class (the pseudo-singleton) just creates the object when getInst() is called and refCount == NULL; delRef checks to see if the pointer passed is a valid pointer to the singleton, and if it is, it decreases *refCount and sets the pointer to NULL, destroying the object/refCount if *refCount reaches zero.
My goal is to create an Inst() class which will get a pointer on creation and release it on destruction, and allow the user to access the singleton's member variables through its -> operator, or something along those lines - but without allowing the user to ever access a pointer to the real thing. Aside from the -> operator, I was thinking of something like defining a conversion operator to MySingleton. Does anyone have ideas about how I might go about doing this?
**EDIT**
Heh nvm, I think I figured it out now (the -> operator really confuses me...). I just had to get operator-> to return a MySingleton* instead of reference, and declare Inst as a friend class of MySingleton ... Operators are so cool...
**EDIT2**
I fixed the code to reflect my changes (also took out the checking for a valid pointer), for anyone who might be interested.
**EDIT3**
Say, is that how smart-pointers work or something?