shared_ptr C++实现
时间: 2023-07-11 14:14:02 浏览: 51
`std::shared_ptr` 是 C++11 标准库中的一种智能指针,它的实现可以借助引用计数来确保在所有引用计数为 0 时自动释放分配的内存。下面是一个简化版的 `shared_ptr` 的实现:
```c++
template <typename T>
class shared_ptr {
public:
shared_ptr(T* ptr = nullptr) : m_ptr(ptr), m_count(new int(1)) {}
shared_ptr(const shared_ptr& other) : m_ptr(other.m_ptr), m_count(other.m_count) { ++(*m_count); }
~shared_ptr() {
if (--(*m_count) == 0) {
delete m_ptr;
delete m_count;
}
}
T& operator*() { return *m_ptr; }
T* operator->() { return m_ptr; }
shared_ptr& operator=(const shared_ptr& other) {
if (this != &other) {
if (--(*m_count) == 0) {
delete m_ptr;
delete m_count;
}
m_ptr = other.m_ptr;
m_count = other.m_count;
++(*m_count);
}
return *this;
}
private:
T* m_ptr;
int* m_count;
};
```
在这个实现中,我们定义了一个 `shared_ptr` 类,它包含了一个指向动态分配内存的指针 `m_ptr` 和一个指向引用计数的指针 `m_count`。在 `shared_ptr` 的构造函数中,我们将 `m_count` 的初始值设为 1,表示当前只有一个 `shared_ptr` 对象引用了这块内存。在 `shared_ptr` 的拷贝构造函数中,我们将 `m_count` 的值加 1,表示多了一个 `shared_ptr` 对象引用了这块内存。在 `shared_ptr` 的析构函数中,我们将 `m_count` 的值减 1,如果引用计数变成了 0,则说明没有任何 `shared_ptr` 对象引用了这块内存,我们就可以释放内存了。在 `shared_ptr` 的赋值运算符中,我们先将 `m_count` 的值减 1,然后检查引用计数是否已经为 0,如果是,则释放内存。然后我们将 `m_ptr` 和 `m_count` 更新为 `other` 的值,并将 `m_count` 的值加 1。
这只是一个简化版的 `shared_ptr` 实现,实际的 `std::shared_ptr` 稍微复杂一些,但基本思路是相同的。