#ifndef CORE_FXCRT_WEAK_PTR_H_
#define CORE_FXCRT_WEAK_PTR_H_
#include <stdint.h>
#include <memory>
#include <utility>
#include "core/fxcrt/retain_ptr.h"
namespace fxcrt {
template <class T, class D = std::default_delete<T>>
class WeakPtr {
public:
WeakPtr() = default;
WeakPtr(const WeakPtr& that) : … { … }
WeakPtr(WeakPtr&& that) noexcept { … }
explicit WeakPtr(std::unique_ptr<T, D> pObj)
: … { … }
WeakPtr(std::nullptr_t arg) { … }
explicit operator bool() const { return m_pHandle && !!m_pHandle->Get(); }
bool HasOneRef() const { … }
T* operator->() { … }
const T* operator->() const { … }
WeakPtr& operator=(const WeakPtr& that) { … }
bool operator==(const WeakPtr& that) const { … }
bool operator!=(const WeakPtr& that) const { … }
T* Get() const { … }
void DeleteObject() { … }
void Reset() { … }
void Reset(std::unique_ptr<T, D> pObj) { … }
void Swap(WeakPtr& that) { … }
private:
class Handle {
public:
explicit Handle(std::unique_ptr<T, D> ptr) : m_pObj(std::move(ptr)) {}
void Reset(std::unique_ptr<T, D> ptr) { m_pObj = std::move(ptr); }
void Clear() {
m_pObj.reset();
}
T* Get() const { return m_pObj.get(); }
T* Retain() {
++m_nCount;
return m_pObj.get();
}
void Release() {
if (--m_nCount == 0)
delete this;
}
bool HasOneRef() const { return m_nCount == 1; }
private:
~Handle() = default;
intptr_t m_nCount = 0;
std::unique_ptr<T, D> m_pObj;
};
RetainPtr<Handle> m_pHandle;
};
}
WeakPtr;
#endif