Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

c++ - Cannot access private member in singleton class destructor

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The code you posted looks doesn't have any problem, so the problem must be in some other part of your source code.

The error message will be preceded by the filename and line number where the problem is occurring. Please look at the line and you'll see a bit of code that is either trying to call delete on a singleton pointer or is trying to construct an instance of singleton.

The error message will look something like this (the file and line number are just an example):

c:pathofile.cpp(41) : error C2248: 'Singleton::~Singleton': cannot access private member declared in class 'Singleton'

So in that case, you would want to see what is happening at line 41 in file.cpp.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...