shared ptr的C++实现
时间: 2023-07-11 13:35:54 浏览: 46
shared_ptr的C++实现主要包括两个部分:控制块和指针。
控制块是一个结构体,用于存储引用计数和其他信息,例如自定义删除器。指针是一个普通的指针,用于指向实际的内存资源。
以下是一个简单的shared_ptr实现:
```
template<class T>
class shared_ptr {
public:
shared_ptr(T* ptr = nullptr) {
if (ptr) {
ref_count_ = new int(1);
ptr_ = ptr;
}
}
~shared_ptr() {
release();
}
shared_ptr(const shared_ptr<T>& other) {
copy(other);
}
shared_ptr<T>& operator=(const shared_ptr<T>& other) {
if (this != &other) {
release();
copy(other);
}
return *this;
}
T* get() const {
return ptr_;
}
int use_count() const {
return *ref_count_;
}
private:
int* ref_count_ = nullptr;
T* ptr_ = nullptr;
void copy(const shared_ptr<T>& other) {
ref_count_ = other.ref_count_;
ptr_ = other.ptr_;
if (ref_count_) {
(*ref_count_)++;
}
}
void release() {
if (ref_count_) {
(*ref_count_)--;
if (*ref_count_ == 0) {
delete ref_count_;
delete ptr_;
}
}
ref_count_ = nullptr;
ptr_ = nullptr;
}
};
```
以上是一个简单的shared_ptr实现,它包括了构造函数、析构函数、拷贝构造函数、赋值运算符、get函数和use_count函数。其中,copy函数用于复制另一个shared_ptr的引用计数和指针,release函数用于释放资源。
需要注意的是,以上实现并没有考虑线程安全和多态等问题,实际使用中需要根据具体情况进行改进。