I’m trying to implement this singleton class. But I encountered this error:
‘Singleton::~Singleton’: cannot access private member declared in class ‘Singleton’
This is flagged in the header file, the last line which contains the closing brace.
Can somebody help me explain what is causing this problem?
Below is my source code.
Singleton.h:
class Singleton
{
public:
static Singleton* Instance()
{
if( !pInstance )
{
if( destroyed )
{
// throw exception
}
else
{
Create();
}
}
return pInstance;
}
private:
static void Create()
{
static Singleton myInstance;
pInstance = &myInstance;
}
Singleton() {}
Singleton( const Singleton& );
Singleton& operator=( const Singleton& );
~Singleton()
{
pInstance = 0;
detroyed = false;
}
static Singleton* pInstance;
static bool destroyed;
};
Singleton.cpp:
Singleton* Singleton::pInstance = 0;
bool Singleton::destroyed = false;
Inside my main function:
Singleton* s = Singleton::Instance();
If I make the destructor as public, then the problem disappears. But a book (Modern C++ Design) says it should be private to prevent users from deleting the instance. I actually need to put some code for cleanup for pInstance and destroyed inside the destructor.
By the way, I’m using Visual C++ 6.0 to compile.
You should probably have let us know that the version of Visual C++ you’re working with is VC6. I can repro the error with that.
At this point, I have no suggestion other than to move up to a newer version of MSVC if possible (VC 2008 is available at no cost in the Express edition).
Just a couple other data points – VC2003 and later have no problem with the
Singletondestructor being private as in your sample.