Re: Singleton base class
On Jun 12, 5:46 pm, Bart van Ingen Schenau <b...@ingen.ddns.info>
wrote:
Vicky wrote:
Can we define a base class say Singleton whose responsibility will be
make its own derived class Singleton too without tempting the internal
structure and representation of derived class. Ex:
No, because if TestClass has a public constructor & destructor, there is
very little to stop a user from writing
Testclass a;
Testclass b;
and defeating the one-instance policy.
class Singleton
{
};
class TestClass : <access specifier> Singleton
{
// No changes are allowed here because it is already well
defined.
};
We can't even add "friend class Singleton" in TestClass.
If you can live with a runtime error, instead of a compile-time error
for attempting to create multiple instances, you could inherit from this
class:
template <class Derived>
class Singleton
{
public:
static Derived& getInstance()
{
static Derived instance;
return instance;
}
protected:
Singleton()
{
if (m_instanceExist)
throw std::logic_error("Singleton policy broken");
m_instanceExists = true;
}
public:
~Singleton() { m_instanceExists = false; }
private:
Singleton(const Singleton&); // not implemented
void operator=(const Singleton&); // not implemented
static bool m_instanceExists;
};
class TestClass : public Singleton<TestClass>
{
// original contents of TestClass
};
{ sig & banner removed. don't quote extraneous material. tia., -mod }
I don't think what you proposed is the solution. Because according to
this, Any body can create object of TestClass without calling
Singleton<Derived>::getInstance().
Since ctor of Singleton is protected and dctor of Singleton is public
both of these functions are easily accessible through TestClass.
In fact, there are problems:
1. TestClass should maintain the behaviour of singleton
2. No modification is allowed in TestClass. We can change their
members access specifier only.
3. The member of TestClass should also be initialize (ctor call).
4. At the time of destruction if dctor should be called.
In general we have to define a class named Singleton whose all derived
class must behave as Singleton without forcing major modification (any
kind of coupling etc.) into derived class.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]