c++ shared_ptr代码实现,定义和声明分开
时间: 2023-11-04 08:42:30 浏览: 52
shared_ptr是C++11中的一个智能指针类,它可以自动管理动态内存的生命周期,避免内存泄漏和悬挂指针等问题。下面是shared_ptr的代码实现,其中定义和声明分开:
// shared_ptr.h
template<typename T>
class shared_ptr {
public:
// 构造函数
shared_ptr();
shared_ptr(T* ptr);
shared_ptr(const shared_ptr<T>& other);
// 析构函数
~shared_ptr();
// 重载运算符
T& operator*() const;
T* operator->() const;
shared_ptr<T>& operator=(const shared_ptr<T>& other);
// 其他成员函数
T* get() const;
void reset();
void reset(T* ptr);
int use_count() const;
private:
T* m_ptr;
int* m_count;
};
// shared_ptr.cpp
template<typename T>
shared_ptr<T>::shared_ptr() : m_ptr(nullptr), m_count(nullptr) {}
template<typename T>
shared_ptr<T>::shared_ptr(T* ptr) : m_ptr(ptr), m_count(new int(1)) {}
template<typename T>
shared_ptr<T>::shared_ptr(const shared_ptr<T>& other) : m_ptr(other.m_ptr), m_count(other.m_count) {
if (m_count) {
(*m_count)++;
}
}
template<typename T>
shared_ptr<T>::~shared_ptr() {
if (m_count) {
(*m_count)--;
if (*m_count == 0) {
delete m_ptr;
delete m_count;
}
}
}
template<typename T>
T& shared_ptr<T>::operator*() const {
return *m_ptr;
}
template<typename T>
T* shared_ptr<T>::operator->() const {
return m_ptr;
}
template<typename T>
shared_ptr<T>& shared_ptr<T>::operator=(const shared_ptr<T>& other) {
if (this != &other) {
if (m_count) {
(*m_count)--;
if (*m_count == 0) {
delete m_ptr;
delete m_count;
}
}
m_ptr = other.m_ptr;
m_count = other.m_count;
if (m_count) {
(*m_count)++;
}
}
return *this;
}
template<typename T>
T* shared_ptr<T>::get() const {
return m_ptr;
}
template<typename T>
void shared_ptr<T>::reset() {
if (m_count) {
(*m_count)--;
if (*m_count == 0) {
delete m_ptr;
delete m_count;
}
m_ptr = nullptr;
m_count = nullptr;
}
}
template<typename T>
void shared_ptr<T>::reset(T* ptr) {
if (m_count) {
(*m_count)--;
if (*m_count == 0) {
delete m_ptr;
delete m_count;
}
}
m_ptr = ptr;
m_count = new int(1);
}
template<typename T>
int shared_ptr<T>::use_count() const {
return m_count ? *m_count : 0;
}