data_abstract_structure.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #pragma once
  8. namespace Data {
  9. // This module suggests a way to hold global data structures, that are
  10. // created on demand and deleted at the end of the app launch.
  11. //
  12. // Usage:
  13. //
  14. // class MyData : public Data::AbstractStruct { .. data .. };
  15. // Data::GlobalStructurePointer<MyData> myData;
  16. // .. somewhere when needed ..
  17. // myData.createIfNull();
  18. class AbstractStructure {
  19. public:
  20. virtual ~AbstractStructure() = 0;
  21. };
  22. inline AbstractStructure::~AbstractStructure() = default;
  23. namespace internal {
  24. void registerAbstractStructure(AbstractStructure **p);
  25. } // namespace
  26. // Must be created in global scope!
  27. // Structure is derived from AbstractStructure.
  28. template <typename Structure>
  29. class GlobalStructurePointer {
  30. public:
  31. GlobalStructurePointer() = default;
  32. GlobalStructurePointer(const GlobalStructurePointer<Structure> &other) = delete;
  33. GlobalStructurePointer &operator=(const GlobalStructurePointer<Structure> &other) = delete;
  34. void createIfNull() {
  35. if (!_p) {
  36. _p = new Structure();
  37. internal::registerAbstractStructure(&_p);
  38. }
  39. }
  40. Structure *operator->() {
  41. Assert(_p != nullptr);
  42. return static_cast<Structure*>(_p);
  43. }
  44. const Structure *operator->() const {
  45. Assert(_p != nullptr);
  46. return static_cast<const Structure*>(_p);
  47. }
  48. explicit operator bool() const {
  49. return _p != nullptr;
  50. }
  51. private:
  52. AbstractStructure *_p;
  53. };
  54. // This method should be called at the end of the app launch.
  55. // It will destroy all data structures created by Data::GlobalStructurePointer.
  56. void clearGlobalStructures();
  57. } // namespace Data