yccheok@gmail.com wrote:[color=blue]
> hello, in a singleton design, i trying to make my parent class having
> protected constructor and destructor. however, the compiler give me
> error when my child, trying to delete itself through parent pointer.
>
> isn't child should have access to parent protected destructor?
>
> thank you.
>
>
> class CMachineFactory
> {
> protected:
> CMachineFactory() {}
> virtual ~CMachineFactory() {}
> __________________________________________________ ________
> CMachineFactory* CSemiAutoMachineFactory::m_pInstance = NULL;
>
> class CSemiAutoMachineFactory : public CMachineFactory
> {
> protected:
> CSemiAutoMachineFactory();
> virtual ~CSemiAutoMachineFactory();
>
> void CSemiAutoMachineFactory::DeleteInstance()
> {
> if(m_pInstance != NULL) {
> delete m_pInstance; // Why not alowed. Isn't child is allowed
> // to access parent's memeber?
>
> m_pInstance = NULL;
> }
> }
>
>
> E:\xxx\semiautomachinefactory.cpp(214) : error C2248:
> 'CMachineFactory::~CMachineFactory' : cannot access protected member
> declared in class 'CMachineFactory'
> E:\Work\rd00072\ScanProxyEx\machinefactory.h(43) : see
> declaration of 'CMachineFactory::~CMachineFactory'[/color]
This is a non-compliant issue with VC++ compiler. The code should
compile, but it will not in VC++ 6.0 or 7.1.
As a workaround, you can create a friend class and let it delete your
singleton.
Here's a workaround example:
template<typename T>
class Singleton
{
protected:
Singleton(){}
~Singleton(){}
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
public:
class FriendClass
{
public:
FriendClass():m_MyClass(new T()){}
~FriendClass(){delete m_MyClass;}
T* m_MyClass;
};
static T& Instance() {
static FriendClass Instance;
return *Instance.m_MyClass;
//Will not compile with the following code in VC++ 6.0 or 7.1
// static T Instance;
// return Instance;
}
};
//The above Singleton template can be used two ways.
//Either by deriving from it, or by declaring the friend class with
fully
//qualified template, and calling the instance member function with
fully
//qualified template function.
class Widget {
private:
Widget(){}
~Widget(){}
Widget& operator=(const Widget&);
Widget(const Widget&);
public:
friend class Singleton<Widget>::FriendClass;
int m_i;
};
class foo : public Singleton<foo>{
private:
foo(){}
~foo(){}
foo& operator=(const foo&);
foo(const foo&);
public:
friend class FriendClass;
int m_i;
};
int main(int, char*)
{
Widget& MyWidget = Singleton<Widget>::Instance();
foo& Myfoo = foo::Instance();