[toc]

# 什么是智能指针

智能指针是为了解决动态内存分配时带来的内存泄漏以及多次释放同一块内存空间而提出的。C11 中封装在了 <memory> 头文件中。 C11 中智能指针包括一下三种: - 共享指针 (shared_ptr): 资源可以被多个指针共享,使用计数机制表明资源被几个指针共享。通过 use_count() 查看资源的所有者的个数,可以通过 unique_ptrweak_ptr 来构造,调用 release() 释放资源的所有权,计数减一,当计数减为 0 时,会自动释放内存空间,从而避免了内存泄漏

  • 独占指针 (unique_prt) : 独享所有权的智能指针,资源只能被一个指针占有,改指针不能拷贝构造和赋值。但可以进行移动构造和移动赋值构造(调用 move() 函数),即一个 unique_ptr 对象赋值给另一个 unique_ptr 对象,可以通过该方法进行赋值。

  • 弱指针 (weak_pr) : 指向 share_ptr 指向的对象,能够解决有 shared_ptr 带来的循环引用问题

# 智能指针实现原理

计数原理 SmartPtr 实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<iostream>
#include<memory>

template <typename T>
class SmartPtr{
private:
T *_ptr;
size_t *_count;

public:
//构造函数中进行内存分配
SmartPtr(T *ptr = nullptr) : _ptr(ptr){
if(_ptr){
_count = new size_t(1);
}else{
_count = new size_t(0);
}
}

//调用一次析构,计数器减一,除非计数器为0,否则不清除
~SmartPtr(){
(*this->count)--;
if(*this->_count == 0){
delete this->_ptr;
delete this->_count;
}
}

SmartPtr(const SmartPtr &ptr) //拷贝构造: 计数+1
{
if(this != &ptr){
this->_ptr = ptr._ptr;
this->_count = ptr._count;
(*this->_count)++;
}
}

SmartPtr &operator=(const SmartPtr &ptr) //赋值运算符重载
{
if(this->_ptr == prt._ptr){
return *this;
}
if(this->_ptr) //将当前的ptr指向的原来的空间的计数-1
{
(*this->count)--;
if(this->_count == 0){
delete this->_ptr;
delete this->_count;
}
}
this->_ptr = ptr._ptr;
this->_count = ptr._count;
(*this->_count)++; //此时ptr指向了新赋值的空间,该空间的计数+1
return *this
}

T &operator*(){
assert(this->_ptr == nullptr);
return *(this->_ptr);
}

T &operator->(){
assert(this->_ptr == nullptr);
return this->_ptr;
}

size_t use_count(){
return *this->count;
}

};

# unique_ptr 权限转移

借助 std::move() 函数

1
2
3
//A作为一个;类
std::unique_ptr<A> ptr1(new A());
std::unique_ptr<A> ptr2 = std::move(ptr1);

# 智能指针出现的问题

更新于

请我喝[茶]~( ̄▽ ̄)~*

Solvarg 微信支付

微信支付

Solvarg 支付宝

支付宝

Solvarg 贝宝

贝宝