DevSight

Singleton with Magic Static in Qt/C++

컴파일러가 C++11을 완전히 지원하는 경우 싱글톤을 구현하는 가장 좋은 방법은 ‘Magic Static’을 사용하는 것이다1. C++11부터는 static 객체 생성이 스레드에 안전하게 보장하도록 표준에 추가되었다2.

singleton.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef SINGLETON_H
#define SINGLETON_H

template <typename T> class Singleton final
{
  public:
    static T &GetInstance()
    {
        static T instance;
        return instance;
    }

  private:
    Singleton() = default;
    ~Singleton() = default;

    Singleton(const Singleton &) = delete;
    Singleton &operator=(const Singleton &) = delete;
    Singleton(Singleton &&) = delete;
    Singleton &operator=(Singleton &&) = delete;
};

#endif // SINGLETON_H
Read More ···