yc*****@gmail.c om wrote:
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 ~CMachineFactor y() {}
_______________ _______________ _______________ _____________
CMachineFactory * CSemiAutoMachin eFactory::m_pIn stance = NULL;
class CSemiAutoMachin eFactory : public CMachineFactory
{
protected:
CSemiAutoMachin eFactory();
virtual ~CSemiAutoMachi neFactory();
void CSemiAutoMachin eFactory::Delet eInstance()
{
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\semiauto machinefactory. cpp(214) : error C2248:
'CMachineFactor y::~CMachineFac tory' : cannot access protected member
declared in class 'CMachineFactor y'
E:\Work\rd00072 \ScanProxyEx\ma chinefactory.h( 43) : see
declaration of 'CMachineFactor y::~CMachineFac tory'
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<typena me 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_MyC lass;
//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<Widge t>::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<Widge t>::Instance() ;
foo& Myfoo = foo::Instance() ;