c++ shared_ptr代码实现,定义和声明分开
时间: 2023-10-17 17:16:58 浏览: 39
定义:
```c++
template<typename T>
class shared_ptr {
public:
//构造函数,创建一个空的shared_ptr
shared_ptr() : ptr(nullptr), ref_count(new size_t(0)) {}
//构造函数,创建一个shared_ptr,指向给定的堆内存
explicit shared_ptr(T* p) : ptr(p), ref_count(new size_t(1)) {}
//拷贝构造函数,创建一个shared_ptr,与另一个shared_ptr共享同一块堆内存
shared_ptr(const shared_ptr<T>& other) : ptr(other.ptr), ref_count(other.ref_count) {
++(*ref_count);
}
//析构函数,释放堆内存,如果引用计数变为0,则删除计数器
~shared_ptr() {
--(*ref_count);
if (*ref_count == 0) {
delete ptr;
delete ref_count;
}
}
//重载赋值运算符
shared_ptr<T>& operator=(const shared_ptr<T>& other) {
if (this != &other) {
--(*ref_count);
if (*ref_count == 0) {
delete ptr;
delete ref_count;
}
ptr = other.ptr;
ref_count = other.ref_count;
++(*ref_count);
}
return *this;
}
//返回指向的对象
T& operator*() const {
return *ptr;
}
//返回指向的对象的指针
T* operator->() const {
return ptr;
}
private:
T* ptr; //指向对象的指针
size_t* ref_count; //引用计数器
};
```
声明:
```c++
template<typename T>
class shared_ptr {
public:
shared_ptr();
explicit shared_ptr(T* p);
shared_ptr(const shared_ptr<T>& other);
~shared_ptr();
shared_ptr<T>& operator=(const shared_ptr<T>& other);
T& operator*() const;
T* operator->() const;
private:
T* ptr;
size_t* ref_count;
};
```