Skip to content

Commit 15f1a48

Browse files
authored
Make ax::WeakPtr support non-const types (#3219)
1 parent 87eb12f commit 15f1a48

1 file changed

Lines changed: 15 additions & 7 deletions

File tree

axmol/base/WeakPtr.h

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ namespace ax
3636

3737
class Object;
3838

39+
template <typename _Ty>
40+
class WeakPtr;
41+
3942
struct WeakObjectItem
4043
{
4144
Object* object{nullptr};
@@ -62,13 +65,18 @@ struct WeakObjectItem
6265
*/
6366
class AX_DLL WeakObjectRegistry
6467
{
68+
friend class Object;
69+
template <typename>
70+
friend class WeakPtr;
71+
6572
public:
6673
static constexpr int CHUNK_SIZE = 32768; // 32K objects per chunk
6774

6875
static WeakObjectRegistry& getInstance();
6976

70-
~WeakObjectRegistry();
77+
virtual ~WeakObjectRegistry();
7178

79+
protected:
7280
// Core interface for lifecycle management
7381
void allocateIndex(ax::Object* obj);
7482
void freeIndex(ax::Object* obj);
@@ -79,7 +87,6 @@ class AX_DLL WeakObjectRegistry
7987
// Get the current serial number for a specific index
8088
uint32_t getSerialNumber(int index) const;
8189

82-
private:
8390
WeakObjectRegistry() = default;
8491

8592
// O(1) Chunked array addressing.
@@ -161,7 +168,7 @@ class WeakPtr
161168
// Attempt to safely retrieve the underlying object
162169
_Ty* get() const
163170
{
164-
static_assert(std::is_base_of<Object, _Ty>::value, "_Ty must inherit from Object");
171+
static_assert(std::is_base_of<Object, std::remove_const_t<_Ty>>::value, "_Ty must inherit from Object");
165172
if (_index == -1)
166173
return nullptr;
167174
return static_cast<_Ty*>(WeakObjectRegistry::getInstance().getObject(_index, _serialNumber));
@@ -212,15 +219,16 @@ class WeakPtr
212219
private:
213220
void assign(_Ty* p)
214221
{
215-
static_assert(std::is_base_of<ax::Object, _Ty>::value, "_Ty must inherit from ax::Object");
222+
using NonConstType = std::remove_const_t<_Ty>;
223+
static_assert(std::is_base_of<ax::Object, NonConstType>::value, "_Ty must inherit from ax::Object");
216224

217225
if (p)
218226
{
219227
// Lazy-load registration: register the object in the global table ONLY
220228
// when a WeakPtr is tracking it for the first time.
221-
if (static_cast<Object*>(p)->_internalIndex == -1)
222-
WeakObjectRegistry::getInstance().allocateIndex(p);
223-
_index = static_cast<Object*>(p)->_internalIndex;
229+
if (p->_internalIndex == -1)
230+
WeakObjectRegistry::getInstance().allocateIndex(const_cast<NonConstType*>(p));
231+
_index = p->_internalIndex;
224232
_serialNumber = WeakObjectRegistry::getInstance().getSerialNumber(_index);
225233
}
226234
else

0 commit comments

Comments
 (0)