shared_ptr是C++11 引入的新特性,用来管理内存,防止内存泄漏
1. shared_ptr 的大小相当于裸指针的两倍,因为shared_ptr内部一般包含了一个指向该资源的裸指针,也包含一个指向该资源的引用计数的裸指针;
void test() {
int *pInt = new int(0);
auto sizePInt = sizeof(pInt); // sizePInt = 8, 指针长度为8
std::shared_ptr<int> sharedInt(new int (1));
auto sizeSharedInt = sizeof(sharedInt); // sizeSharedInt = 16,因为包含了两个指针
}
2. 引用计数器的内存必须是动态分配的;
3. 引用计数器的递增和递减必须是原子操作。
shared_ptr 的内存结构(参考 Effective Modern C++)
shared_ptr 的简单实现
#ifndef __SHARED_PTR_H__
#define __SHARED_PTR_H__
template<typename T>
class Shared_ptr {
public:
Shared_ptr(T* ptr) : m_ptr(ptr) {
if (ptr != nullptr) {
m_pCount = new int(1);
}
else {
m_pCount = new int(0); //当指针为空时,*m_pCount = 0
}
}
~Shared_ptr() {
if (*m_pCount > 0) {
(*m_pCount)--;
}
if (*m_pCount == 0) { //当*m_pCount为0时,释放相关资源
delete m_pCount;
m_pCount = nullptr;
delete m_ptr;
m_ptr = nullptr;
}
}
Shared_ptr(const Shared_ptr& other) {
if (&other != this) {
m_pCount = other.m_pCount;
if (*m_pCount > 0) { // 排除 other.m_ptr= nullptr的时,other.m_pCount = 0的情况
(*m_pCount)++;
}
m_ptr = other.m_ptr;
}
}
Shared_ptr& operator= (const Shared_ptr &other) {
if (&other == this) {
return *this;
}
if (*m_pCount > 0) {
m_pCount--;
}
if (*m_pCount == 0) { //释放之前申请的内存
if (m_ptr == nullptr) {
delete m_ptr;
}
if (m_pCount == nullptr) {
delete m_pCount;
}
}
m_pCount = other.m_pCount;
if (*m_pCount > 0) {
(*m_pCount)++;
}
m_ptr = other.m_ptr;
return *this;
}
T& operator*() const {
return *m_ptr;
}
T* operator->() const {
return m_ptr;
}
T* get() {
return m_ptr;
}
long int use_count() {
return *m_pCount;
}
private:
int* m_pCount = nullptr;
T* m_ptr = nullptr;
};
#endif