Kylin/DataStructure/SharedPointer.h
2023-12-27 10:29:16 +08:00

52 lines
1.2 KiB
C++

#ifndef SHAREDPOINTER_H
#define SHAREDPOINTER_H
#include "Pointer.h"
namespace Kylin {
template <typename T>
class SharedPointer : public Pointer<T> {
public:
SharedPointer(T *p) {
if (p == nullptr) return;
this->m_pointer = p;
m_counter = new size_t(1);
}
SharedPointer(const SharedPointer &obj) {
if (obj.m_counter == nullptr) return;
m_counter = obj.m_counter;
this->m_pointer = obj.m_pointer;
(*m_counter)++;
}
SharedPointer &operator=(const SharedPointer &obj) {
if (this != &obj) {
clear();
m_counter = obj.m_counter;
this->m_pointer = obj.m_pointer;
(*m_counter)++;
}
}
void clear() {
if (m_counter == nullptr) return;
(*m_counter)--;
if (*m_counter == 0) {
delete m_counter;
delete this->m_pointer;
}
this->m_pointer = nullptr;
m_counter = nullptr;
}
bool operator==(const SharedPointer &obj) const { return (this->m_pointer == obj.m_pointer); }
~SharedPointer() { clear(); }
private:
size_t *m_counter = nullptr;
};
} // namespace Kylin
#endif // SHAREDPOINTER_H