fork download
  1. #include <stdio.h>
  2. #include <vector>
  3. #include <memory>
  4. #include <mutex>
  5.  
  6. template <typename T>
  7. class Singleton : public T {
  8. private:
  9. static std::unique_ptr<T> instance;
  10. static std::mutex mutex;
  11. Singleton();
  12.  
  13. Singleton<T>(const Singleton<T>&) = delete;
  14. Singleton<T>&operator=(const Singleton<T>&) = delete;
  15.  
  16. public:
  17. static T& getInstance() {
  18. {
  19. std::lock_guard<std::mutex> lock(mutex);
  20. if (nullptr == instance) {
  21. instance.reset(new T {});
  22. }
  23. }
  24. return *instance.get();
  25. }
  26. static void deleteInstance() {
  27. instance.reset();
  28. }
  29. ~Singleton();
  30. };
  31.  
  32. template<typename T>
  33. std::unique_ptr<T> Singleton<T>::instance { nullptr };
  34.  
  35. template<typename T>
  36. std::mutex Singleton<T>::mutex {};
  37.  
  38. template<typename T>
  39. inline Singleton<T>::Singleton() {}
  40.  
  41. template<typename T>
  42. inline Singleton<T>::~Singleton() {}
  43.  
  44. int main() {
  45. auto & vec = Singleton<std::vector<int>>::getInstance();
  46. vec.push_back(1);
  47. vec.push_back(2);
  48. vec.push_back(3);
  49. for (auto v : vec) {
  50. printf("%d\n", v);
  51. }
  52. Singleton<std::vector<int>>::deleteInstance();
  53. return 0;
  54. }
Success #stdin #stdout 0s 16056KB
stdin
Standard input is empty
stdout
1
2
3