singleton.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (C) 2016 Alexander Makarov
  3. *
  4. * Source:
  5. * https://wiki.qt.io/Qt_thread-safe_singleton
  6. *
  7. * This file is a part of Breakpad-qt library.
  8. *
  9. * This library is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * This library is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. */
  20. #ifndef SINGLETON
  21. #define SINGLETON
  22. #include <QtGlobal>
  23. #include <QScopedPointer>
  24. #include "call_once.h"
  25. template <class T>
  26. class Singleton
  27. {
  28. public:
  29. static T& instance()
  30. {
  31. qCallOnce(init, flag);
  32. return *tptr;
  33. }
  34. static void init()
  35. {
  36. tptr.reset(new T);
  37. }
  38. private:
  39. Singleton() {}
  40. ~Singleton() {}
  41. Q_DISABLE_COPY(Singleton)
  42. static QScopedPointer<T> tptr;
  43. static QBasicAtomicInt flag;
  44. };
  45. template<class T> QScopedPointer<T> Singleton<T>::tptr(0);
  46. template<class T> QBasicAtomicInt Singleton<T>::flag = Q_BASIC_ATOMIC_INITIALIZER(CallOnce::CO_Request);
  47. #endif // SINGLETON