c++写一个简易版的shared_ptr
时间: 2023-04-11 19:01:09 浏览: 67
好的,我可以回答这个问题。shared_ptr 是一个智能指针,可以用来管理动态分配的内存。下面是一个简易版的 shared_ptr 实现:
```c++
template <typename T>
class shared_ptr {
public:
shared_ptr(T* ptr = nullptr) : ptr_(ptr), count_(new int(1)) {}
shared_ptr(const shared_ptr& other) : ptr_(other.ptr_), count_(other.count_) {
++(*count_);
}
~shared_ptr() {
if (--(*count_) == 0) {
delete ptr_;
delete count_;
}
}
shared_ptr& operator=(const shared_ptr& other) {
if (this != &other) {
if (--(*count_) == 0) {
delete ptr_;
delete count_;
}
ptr_ = other.ptr_;
count_ = other.count_;
++(*count_);
}
return *this;
}
T& operator*() const {
return *ptr_;
}
T* operator->() const {
return ptr_;
}
int use_count() const {
return *count_;
}
private:
T* ptr_;
int* count_;
};
```
这个实现使用了计数器来记录有多少个 shared_ptr 共享同一个对象的所有权。当最后一个 shared_ptr 被销毁时,它会释放对象的内存。