ezEngine  Milestone 7
ResourceHandle.h
1 #pragma once
2 
3 #include <Core/Basics.h>
4 
5 class ezResourceBase;
6 
7 // These out-of-line helper functions allow to forward declare resource handles without knowledge about the resource class.
8 EZ_CORE_DLL void IncreaseResourceRefCount(ezResourceBase* pResource);
9 EZ_CORE_DLL void DecreaseResourceRefCount(ezResourceBase* pResource);
10 
23 template<typename ResourceType>
24 class ezResourceHandle
25 {
26 public:
27 
30  {
31  m_pResource = NULL;
32  }
33 
35  ezResourceHandle(ResourceType* pResource)
36  {
37  m_pResource = pResource;
38 
39  if (m_pResource)
40  IncreaseResourceRefCount(reinterpret_cast<ezResourceBase*>(m_pResource));
41  }
42 
45  {
46  m_pResource = rhs.m_pResource;
47 
48  if (m_pResource)
49  IncreaseResourceRefCount(reinterpret_cast<ezResourceBase*>(m_pResource));
50  }
51 
54  {
55  m_pResource = rhs.m_pResource;
56  rhs.m_pResource = NULL;
57  }
58 
61  {
62  Invalidate();
63 
64  m_pResource = rhs.m_pResource;
65 
66  if (m_pResource)
67  IncreaseResourceRefCount(reinterpret_cast<ezResourceBase*>(m_pResource));
68  }
69 
72  {
73  Invalidate();
74 
75  m_pResource = rhs.m_pResource;
76  rhs.m_pResource = NULL;
77  }
78 
81  {
82  Invalidate();
83  }
84 
86  bool IsValid() const
87  {
88  return m_pResource != NULL;
89  }
90 
92  void Invalidate()
93  {
94  if (m_pResource)
95  DecreaseResourceRefCount(reinterpret_cast<ezResourceBase*>(m_pResource));
96 
97  m_pResource = NULL;
98  }
99 
101  EZ_FORCE_INLINE bool operator==(const ezResourceHandle<ResourceType>& rhs) const
102  {
103  return m_pResource == rhs.m_pResource;
104  }
105 
107  EZ_FORCE_INLINE bool operator!=(const ezResourceHandle<ResourceType>& rhs) const
108  {
109  return m_pResource != rhs.m_pResource;
110  }
111 
112 private:
113  // you must go through the resource manager to get access to the resource pointer
114  friend class ezResourceManager;
115 
116  ResourceType* m_pResource;
117 };
118 
119