简体   繁体   中英

definition of static variable inside a class member function

I am learning singleton design pattern and came across this piece of code

class Singleton
{
    private:
        static Singleton * pinstance_;
        static std::mutex mutex_;
    protected:
        static Singleton *GetInstance(const std::string& value);
};


Singleton* Singleton::pinstance_{nullptr}; //can this line be removed?
std::mutex Singleton::mutex_; //can this line be removed?

Singleton *Singleton::GetInstance(const std::string& value)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (pinstance_ == nullptr)
    {
        pinstance_ = new Singleton(value);
    }
    return pinstance_;
}

since pinstance_ and mutex_ are all members of Singleton class, they are accessible by GetInstance method. So my question is: can these two definition lines be removed?

No, they can't be removed but they can be moved to local static variables of the method.

class Singleton
{
    protected:
        static Singleton *GetInstance(const std::string& value);
};

Singleton *Singleton::GetInstance(const std::string& value)
{
    static Singleton* pinstance_{nullptr};
    static std::mutex mutex_;

    std::lock_guard<std::mutex> lock(mutex_);
    if (pinstance_ == nullptr)
    {
        pinstance_ = new Singleton(value);
    }
    return pinstance_;
}

Also note, no guards required for initializing static variables. The compiler does it for you. Is local static variable initialization thread-safe in C++11? [duplicate]

Singleton *Singleton::GetInstance(const std::string& value)
{
    static Singleton* pinstance_ = new Singleton(value);
    return pinstance_;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM