首页 文章

无法访问singleton类析构函数中的私有成员

提问于
浏览
4

我正在尝试实现这个单例类 . 但是我遇到了这个错误:

'Singleton :: ~Singleton':无法访问类'Singleton'中声明的私有成员 . 这在头文件中标记,最后一行包含右括号 .

有人可以帮我解释导致这个问题的原因吗?以下是我的源代码 .

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;

在我的主要功能内:

Singleton* s = Singleton::Instance();

如果我将析构函数设为公共,那么问题就会消失 . 但是一本书(Modern C Design)说它应该是私有的,以防止用户删除该实例 . 我实际上需要为pInstance放置一些清理代码并在析构函数中销毁 .

顺便说一句,我正在使用Visual C 6.0进行编译 .

5 回答

  • 2

    我不是C或VC专家,但你的例子看起来类似于this page上描述的那个...作者称之为编译器错误 .

  • 2

    我个人没有把析构函数放在我的单身人士中,除非我使用模板单例类,但后来我保护它们 .

    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(){};
    
    };
    

    然后把我的课写成

    class LogWriter : public Singleton<LogWriter>
    {
    friend class Singleton<LogWriter>;
    }
    
  • 0

    您发布的代码看起来没有任何问题,因此问题必须出在源代码的其他部分 .

    错误消息前面将出现问题所在的文件名和行号 . 请查看该行,您将看到一些代码尝试在单例指针上调用delete或尝试构造单例实例 .

    错误消息看起来像这样(文件和行号只是一个例子):

    c:\path\to\file.cpp(41) : error C2248: 'Singleton::~Singleton': cannot access private member declared in class 'Singleton'
    

    因此,在这种情况下,您可能希望查看file.cpp中第41行发生的情况 .

  • 2

    您应该告诉我们您正在使用的Visual C的版本是VC6 . 我可以用这个来重现错误 .

    此时,除了尽可能升级到更新版本的MSVC之外,我没有任何建议(在Express版本中免费提供VC 2008) .

    只有几个其他数据点 - VC2003及更高版本没有问题, Singleton 析构函数在您的示例中是私有的 .

  • -1
    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;
              }
    
         }
    };
    

相关问题