开发者

Using a Static Class function to create a Singleton object/instance

I am trying to create a static member function that returns a pointer to one instance of the class. Is this possible in C++?

    class DynamicMemoryLog
{
    // Singleton Class:

    public:

        static DynamicMemoryLog* CreateLog();
        void   AddIObject( IUnknown* obj );
        void   ReleaseDynamicMemory();

    private开发者_如何学JAVA:
        // static DynamicMemoryLog* instance;
        static bool isAlive;  // used to determine is an instance of DynamicMemoryLog already exists

        DynamicMemoryLog();
        ~DynamicMemoryLog();

        std::vector <IUnknown*> iObjectList;
};

This function below should create a new instance of the class & return a pointer to that object, but the compiler will not allow me to define a static function of the class if it returns a pointer(I think thats why it wont compile?):

static DynamicMemoryLog* DynamicMemoryLog :: CreateLog()
{
    // Post:

    if ( !isAlive )   // ( instance == NULL; )
    {
       DynamicMemoryLog* instance  = new DynamicMemoryLog();
       return instance;
    }

    return NULL;
}


The particular error you're getting is that when implementing a static member function, you don't repeat the static keyword. Fixing this should resolve the error.

Independently, there's something a bit odd with your code. You claim that this object is a singleton, but each call to CreateLog will create a new instance of the class. Do you really want this behavior, or do you want there to be many copies? I'd suggest looking into this before proceeding.


Here's the simplest solution, but not thread-safe. For analysis in detail, have a look at this article.

class DynamicMemoryLog 
{
public:
   static DynamicMemoryLog* GetInstance();
private:
   DynamicMemoryLog();
   static DynamicMemoryLog* m_pInstance;
}

DynamicMemoryLog* DynamicMemoryLog::GetInstance()
{
   if(!m_pInstance)    
   {
      m_pInstance = new DynamicMemoryLog();       
   }     

   return m_pInstance;
}


I usually do something like this:

class Singleton
{
    public:

        static Singleton* get()
        {
            static Singleton instance;
            return &instance;
        }
};

This way you won't have any nasty memory management issues.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜