singleton类

作者: 老练子丶2017 | 来源:发表于2017-11-16 15:24 被阅读0次

    支持多线程的单例类

    singleton.h:

    #ifndef _SINGLETON_H

    #define _SINGLETON_H

    #include "lock.h"

    template<class type>

    class Singleton : public NonCopy

    {

    public:

    Singleton() : instance_(NULL) {

    }

    ~Singleton() {

    if (instance_ != NULL) {

    delete instance_;

    instance_ = NULL;

    }

    }

    type *Get() {

    if (instance_ == NULL) {

    ScopeLock scope_lock(&lock_);

    if (instance_ == NULL) {

    type *temp = new type;

    instance_ = temp;

    }

    }

    return instance_;

    }

    type &operator*() {

    return *Get();

    }

    type *operator->() {

    return Get();

    }

    private:

    SpinLock lock_;

    type *volatile instance_;

    };

    #endif // _SINGLETON_H

    singleton.cpp

    #include "singleton.h"

    class Test{

    public: void print() {

    cout << "test" << endl;

    }

    static Test* GetInstance() {

    static Singleton<Test> test;

    return test.Get();

    }

    };

    int main()

    {

    Test::GetInstance()->print();

    return 0;

    }

    编译:g++ -o singleton singleton.cpp lock.cpp -lpthread

    相关文章

      网友评论

        本文标题:singleton类

        本文链接:https://www.haomeiwen.com/subject/uewlvxtx.html