Cannot access private member in singleton class destructor

前端 未结 5 887
感动是毒
感动是毒 2020-12-21 05:24

I\'m trying to implement this singleton class. But I encountered this error:

\'Singleton::~Singleton\': cannot access private member declared in class \'Singleton\'

相关标签:
5条回答
  • 2020-12-21 05:39
    class Singleton
    {
         static Singleton *pInstance = NULL;  
         Singleton(){};
    
         public:
    
        static Singleton * GetInstance() {
    
              if(!pInstance)
              {
                   pInstance = new Singleton();
              }
              return pInstance;
         }
    
         static void  RemoveInstance() {
    
              if(pInstance)
              {
                   delete pInstance;
                   pInstance = NULL;
              }
    
         }
    };
    
    0 讨论(0)
  • 2020-12-21 05:44

    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 Singleton destructor being private as in your sample.

    0 讨论(0)
  • 2020-12-21 05:47

    I'm no C++ or VC expert, but your example looks similar to the one described on this page ... which the author calls a compiler bug.

    0 讨论(0)
  • 2020-12-21 05:51

    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:\path\to\file.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.

    0 讨论(0)
  • 2020-12-21 05:55

    Personally i haven't put destructors in my singletons unless i am using a template singleton class, but then i make them protected.

    template<class T>
    class Singleton
    {
    public:
        static T &GetInstance( void )
        {
            static T obj;
            return obj;
        }
    
        static T *GetInstancePtr( void )
        {
            return &(GetInstance());
        }
    
    protected:
        virtual ~Singleton(){};
        Singleton(){};
    
    };
    

    then write my class as

    class LogWriter : public Singleton<LogWriter>
    {
    friend class Singleton<LogWriter>;
    }
    
    0 讨论(0)
提交回复
热议问题