c++ 手写智能指针
时间: 2023-12-18 18:29:26 浏览: 95
以下是一个简单的C++手写智能指针的实现,它使用引用计数来跟踪指针的使用情况,确保在不再需要指针时正确地释放内存:
```c++
template <typename T>
class SmartPtr {
public:
SmartPtr(T* ptr = nullptr) : ptr_(ptr) {
if (ptr_) {
shared_count_ = new int(1);
}
}
~SmartPtr() {
release();
}
SmartPtr(const SmartPtr& other) {
ptr_ = other.ptr_;
if (ptr_) {
shared_count_ = other.shared_count_;
(*shared_count_)++;
}
}
template <typename U>
SmartPtr(const SmartPtr<U>& other) {
ptr_ = other.get();
if (ptr_) {
shared_count_ = other.get_shared_count();
(*shared_count_)++;
}
}
SmartPtr& operator=(const SmartPtr& other) {
if (this != &other) {
release();
ptr_ = other.ptr_;
if (ptr_) {
shared_count_ = other.shared_count_;
(*shared_count_)++;
}
}
return *this;
}
T& operator*() const {
return *ptr_;
}
T* operator->() const {
return ptr_;
}
T* get() const {
return ptr_;
}
int use_count() const {
return *shared_count_;
}
int* get_shared_count() const {
return shared_count_;
}
void reset(T* ptr = nullptr) {
release();
ptr_ = ptr;
if (ptr_) {
shared_count_ = new int(1);
}
}
private:
void release() {
if (ptr_ && --(*shared_count_) == 0) {
delete ptr_;
delete shared_count_;
}
}
T* ptr_;
int* shared_count_;
};
```
阅读全文