目录
[4.1 auto_ptr和unique_ptr的实现](#4.1 auto_ptr和unique_ptr的实现)
[4.2 shared_ptr的实现1](#4.2 shared_ptr的实现1)
[4.3 delete的问题](#4.3 delete的问题)
[4.3.1 方案一](#4.3.1 方案一)
[4.3.2 方案二](#4.3.2 方案二)
[4.3.2.1 仿函数充当删除器](#4.3.2.1 仿函数充当删除器)
[4.3.2.2 lambda充当删除器](#4.3.2.2 lambda充当删除器)
[4.3.2.3 函数指针充当删除器](#4.3.2.3 函数指针充当删除器)
[4.4 unique_ptr和shared_ptr定制删除器的区别](#4.4 unique_ptr和shared_ptr定制删除器的区别)
[4.5 shared_ptr的实现2(删除器)](#4.5 shared_ptr的实现2(删除器))
[5.1 shared_ptr循环引用问题](#5.1 shared_ptr循环引用问题)
[5.2 weak_ptr](#5.2 weak_ptr)
[8.1 什么是内存泄漏,内存泄漏的危害](#8.1 什么是内存泄漏,内存泄漏的危害)
[8.2 如何检测内存泄漏](#8.2 如何检测内存泄漏)
[8.3 如何避免内存泄漏](#8.3 如何避免内存泄漏)
一、智能指针的使用场景分析
下面程序中我们可以看到,new了以后,我们也delete了,但是因为抛异常导,后面的delete没有得到执行,所以就内存泄漏了,所以我们需要new以后捕获异常,捕获到异常后delete内存,再把异常抛出,但是因为new本身也可能抛异常,连续的两个new和下面的Divide都可能会抛异常,让我们处理起来很麻烦。智能指针放到这样的场景里面就让问题简单多了。
cpp
#include<iostream>
#include<string>
using namespace std;
double Divide(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
{
throw "Divide by zero condition!";
}
else
{
return (double)a / (double)b;
}
}
void Func()
{
int* array1 = new int[10];
int* array2 = new int[10];
int len, time;
cin >> len >> time;
cout << Divide(len, time) << endl;
cout << "delete []" << array1 << endl;
delete[] array1;
cout << "delete []" << array2 << endl;
delete[] array2;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (const exception& e)
{
cout << e.what() << endl;
}
catch (...)
{
cout << "未知异常" << endl;
}
return 0;
}
当我们在Func函数里面new资源,然后调用Divide函数,如果divide函数不抛异常,执行完divide函数后回到Func函数,可以释放new出来的资源,但是如果抛出异常,就会跳转到main函数中的catch语句里面,并且没有释放在Func中new出来的资源就会导致内存泄漏。
修改代码如下所示,我们在Func中加一个捕获任意异常的catch语句,当divide抛出异常时,在Func函数中捕获,然后释放在之前new出来的资源,然后重新抛出异常。
cpp
#include<iostream>
#include<string>
using namespace std;
double Divide(int a, int b)
{
// 当b == 0时抛出异常
if (b == 0)
{
throw "Divide by zero condition!";
}
else
{
return (double)a / (double)b;
}
}
void Func()
{
//这里可以看到如果发生除0错误抛出异常,另外下面的array和array2没有得到释放。
//所以这里捕获异常后并不处理异常,异常还是交给外面处理,这里捕获了再重新抛出去。
//但是如果array2new的时候抛异常呢,就还需要套一层捕获释放逻辑,这里更好解决方案
//是智能指针,否则代码太戳了
int* array1 = new int[10];
int* array2 = new int[10]; // 抛异常呢
try
{
int len, time;
cin >> len >> time;
cout << Divide(len, time) << endl;
}
catch (...)
{
cout << "delete []" << array1 << endl;
cout << "delete []" << array2 << endl;
delete[] array1;
delete[] array2;
throw; // 异常重新抛出,捕获到什么抛出什么
}
// ...
cout << "delete []" << array1 << endl;
delete[] array1;
cout << "delete []" << array2 << endl;
delete[] array2;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (const exception& e)
{
cout << e.what() << endl;
}
catch (...)
{
cout << "未知异常" << endl;
}
return 0;
}
但是如果new抛出异常了呢?new本身也会抛出异常的,如果第2个new抛出异常呢?就需要捕获异常来释放第一个new出来的空间。
如果有很多个new呢?每一个new都可能会抛出异常,那不是需要写很多的try catch嘛?
所以C++设计了RAII的东西来管理资源。(将资源委托给一个对象)
二、RAII和智能指针的设计思路
- RAll是Resource Acquisition Is Initialization的缩写,他是一种管理资源的类的设计思想,本质是一种利用对象生命周期来管理获取到的动态资源,避免资源泄漏,这里的资源可以是内存、文件指针、网络连接、互斥锁等等。RAIl在获取资源时把资源委托给一个对象,接着控制对资源的访问,资源在对象的生命周期内始终保持有效,最后在对象析构的时候释放资源,这样保障了资源的正常释放,避免资源泄漏问题。
- 智能指针类除了满足RAII的设计思路,还要方便资源的访问,所以智能指针类还会像迭代器类一样,重载operator*/operator->/operator[]等运算符,方便访问资源。
下面实现一个简单的智能指针
cpp
#include<iostream>
#include<string>
using namespace std;
template<class T>
class SmattPtr
{
public:
SmattPtr(T* ptr)
:_ptr(ptr)
{ }
~SmattPtr()
{
cout << "delete[]" << _ptr << endl;
delete[] _ptr;
}
//重载运算符,模拟指针的行为,方便访问资源
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
T& operator[](size_t i)
{
return _ptr[i];
}
private:
T* _ptr;
};
double Divide(int a, int b)
{
if (b == 0)
{
throw "Divide by zero condition";
}
else
{
return (double)a / (double)b;
}
}
void Func()
{
SmattPtr<int> sp1 = new int[10];
SmattPtr<int> sp2 = new int[10];
for (size_t i = 0; i < 10; i++)
{
sp1[i] = sp2[i] = i;
}
int len, time;
cin >> len >> time;
cout << Divide(len, time) << endl;
}
int main()
{
try
{
Func();
}
catch (const char* errmsg)
{
cout << errmsg << endl;
}
catch (const exception& e)
{
cout << e.what() << endl;
}
catch (...)
{
cout << "未知异常" << endl;
}
}
我们将new出来的资源给一个SmartPtr类来进行管理。
1:如果没有divide函数没有抛异常,当Func函数正常结束的时候会调用SmartPtr的析构函数来进行资源释放。如下图所示(正常结束):
2:如果divide函数抛出异常,会跳转到main函数中的catch语句里面。就会结束Func函数的栈帧,当Func函数的栈帧结束之后,就会销毁SmartPtr对象,然后就会调用析构函数来释放资源。如下图所示(抛异常):
**3:如果第一个new抛异常,**没有任何对象被构造出来,没有任何内存泄漏,程序直接跳去捕获异常,安全退出。第二个new都不会被执行。
**4:如果第二个new抛异常,**第一个智能指针sp1会自动析构→内存安全释放,第二个智能指针sp2根本没构造→无需释放。无内存泄漏,程序安全退出。
三、C++标准库智能指针的使用
- C++标准库中的智能指针都在**<memory>** 这个头文件下面,我们包含<memory>就可以是使用了,智能指针有好几种,除了weak_ptr他们都符合RAll和像指针一样访问的行为,原理上而言主要是解决智能指针拷贝时的思路不同。
智能指针的拷贝问题:
我们定义了一个智能指针来管理资源,SmartPtr<int> sp1=new int[10];现在我想拷贝一下智能指针对象,SmartPtr<int> sp1(sp1);
现在会出现浅拷贝问题,因为我们在SmartPtr里面没有写拷贝构造,所以会默认生成一个浅拷贝的拷贝构造函数。这就会导致两个智能指针对象指向同一块内存资源,当程序结束之后,会析构两次而导致程序崩溃。
那我们需要在智能指针里面写一个深拷贝的拷贝构造函数嘛?
智能指针模拟的是原生指针的行为,我们将int* sp2=sp1;sp1和sp2就会指向同一块内存资源,不会让sp2指向新的相同的内存资源。所以我们在智能指针里面不应该写一个深拷贝的拷贝构造函数。智能指针想要的是sp1和sp2指向同一块资源,sp1和sp2共同管理。
但是析构多次的问题如何解决呢?拷贝构造的如何实现呢?下面来看一下库里面的智能指针
**1:auto_ptr:**拷贝时把被拷贝对象的资源的管理权转移给拷贝对象,强烈建议不要使用auto_ptr
**2:unique_ptr:**不支持拷贝,只支持移动。如果不需要拷贝的场景就非常建议使用他。
**3:shared_ptr:**支持拷贝,也支持移动。
- auto_ptr是C++98时设计出来的智能指针,他的特点是拷贝时把被拷贝对象的资源的管理权转移给拷贝对象,这是一个非常糟糕的设计,因为他会到被拷贝对象悬空,访问报错的问题,C++11设计出新的智能指针后,强烈建议不要使用auto_ptr。其他C++11出来之前很多公司也是明令禁止使用这个智能指针的。
cpp#include<iostream> #include<memory> using namespace std; struct Date { int _year; int _month; int _day; Date(int year = 1, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) { } ~Date() { cout << "~Date()" << endl; } }; int main() { auto_ptr<Date> ap1(new Date); auto_ptr<Date> ap2(ap1); return 0; }我们运行之后,Date只析构了一次,程序没有崩溃,这是因为ap1没有指向Date资源了,只有ap2指向Date资源,如下图所示:
拷贝构造前:
拷贝构造后:
我们可以看见ap1指向一个null,ap2指向ap1原本的资源。他的特点是拷贝时把被拷贝对象的资源的管理权转移给拷贝对象,这是一个非常糟糕的设计,因为他会到被拷贝对象悬空,访问报错的问题,此时我们使用ap1就不能访问Date资源了。
- unique_ptr是C++11设计出来的智能指针,他的名字翻译出来是唯一指针,他的特点的不支持拷贝,只支持移动。如果不需要拷贝的场景就非常建议使用他。
cpp#include<iostream> #include<memory> using namespace std; struct Date { int _year; int _month; int _day; Date(int year = 1, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) { } ~Date() { cout << "~Date()" << endl; } }; int main() { unique_ptr<Date> up1(new Date); //不支持拷贝 //unique_ptr<Date> up2(up1); //支持移动,但是移动之后up1也悬空,所以使用移动要谨慎 unique_ptr<Date> up3(move(up1)); return 0; }
- shared_ptr是C++11设计出来的智能指针,他的名字翻译出来是共享指针,他的特点是支持拷贝,也支持移动。如果需要拷贝的场景就需要使用他了。底层是用引用计数的方式实现的。
cpp#include<iostream> #include<memory> using namespace std; struct Date { int _year; int _month; int _day; Date(int year = 1, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) { } ~Date() { cout << "~Date()" << endl; } }; int main() { shared_ptr<Date> sp1(new Date); shared_ptr<Date> sp2(sp1); shared_ptr<Date> sp3(sp2); cout << sp3.use_count() << endl; cout << sp1->_year << endl; cout << sp2->_year << endl; cout << sp3->_year << endl; return 0; }
- weak_ptr是C++11设计出来的智能指针,他的名字翻译出来是弱指针,他完全不同于上面的智能指针,他不支持RAll,也就意味着不能用它直接管理资源,weak_ptr的产生本质是要解决shared_ptr的一个循环引用导致内存泄漏的问题。具体细节下面我们再细讲。(见五)
- 智能指针析构时默认是进行delete释放资源,这也就意味着如果不是new出来的资源,交给智能指针管理,析构时就会崩溃。智能指针支持在构造时给一个删除器,所谓删除器本质就是一个可调用对象,这个可调用对象中实现你想要的释放资源的方式,当构造智能指针时,给了定制的删除器,在智能指针析构时就会调用删除器去释放资源。因为new[]经常使用,所以为了简洁一点,unique_ptr和shared_ptr都特化了一份[]的版本,使用时unique_ptr<Date[]> up1(new Date[5]);shared_ptr<Date[]>sp1(new Date[5]);就可以管理new[]的资源。(见4.3)
- template <class T, class Args> shared_ptr<T> make_shared(Args&&...args);
- shared_ptr除了支持用指向资源的指针构造,还支持make_shared用初始化资源对象的值直接构造。如下所示:
cpp#include<iostream> #include<memory> using namespace std; struct Date { Date(int year = 1, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) { } ~Date() { cout << "~Date()" << endl; } int _year; int _month; int _day; }; int main() { shared_ptr<Date> sp1(new Date(2024, 9, 11)); shared_ptr<Date> sp2 = make_shared<Date>(2024, 9, 11); return 0; }
- shared_ptr和unique_ptr都支持了operator bool的类型转换,如果智能指针对象是一个空对象没有管理资源,则返回false,否则返回true,意味着我们可以直接把智能指针对象给if判断是否为空。代码如下所示:
cpp#include<iostream> #include<memory> using namespace std; struct Date { Date(int year = 1, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) { } ~Date() { cout << "~Date()" << endl; } int _year; int _month; int _day; }; int main() { shared_ptr<Date> sp1(new Date(2024, 9, 11)); shared_ptr<Date> sp2 = make_shared<Date>(2024, 9, 11); shared_ptr<Date> sp3; //if(sp1.operator bool()) if (sp1) cout << "sp1 is not nullptr" << endl; else cout << "sp1 is nullptr" << endl; if (sp3) cout << "sp3 is not nullptr" << endl; else cout << "sp3 is nullptr" << endl; return 0; }
- shared_ptr和unique_ptr构造函数都使用explicit 修饰,防止普通指针隐式类型转换成智能指针对象。如下所示:
cpp#include<iostream> #include<memory> using namespace std; struct Date { Date(int year = 1, int month = 1, int day = 1) :_year(year) , _month(month) , _day(day) { } ~Date() { cout << "~Date()" << endl; } int _year; int _month; int _day; }; int main() { // 报错 shared_ptr<Date> sp5 = new Date(2024, 9, 11); unique_ptr<Date> sp6 = new Date(2024, 9, 11); return 0; }
四、智能指针的原理
4.1 auto_ptr和unique_ptr的实现
- 下面我们模拟实现了auto_ptr和unique_ptr的核心功能,这两个智能指针的实现比较简单,大家了解一下原理即可。auto_ptr的思路是拷贝时转移资源管理权给被拷贝对象,这种思路是不被认可的,也不建议使用。unique_ptr的思路是不支持拷贝。
auto_ptr的模拟实现:
cpp#include<iostream> #include<memory> using namespace std; namespace zx { template<class T> class auto_ptr { public: auto_ptr(T* ptr) :_ptr(ptr) { } auto_ptr(auto_ptr<T>& sp) :_ptr(sp._ptr) { sp._ptr = nullptr; } auto_ptr<T>& operator=(auto_ptr<T>& ap) { if (this != &ap) { if (_ptr) delete _ptr; _prt = ap._ptr; ap._ptr = nullptr; } return *this; } ~auto_ptr() { if (_ptr) { cout << "delete:" << _ptr<< endl; delete _ptr; } } T& operator*() { return *_ptr; } T* operator->() { return _ptr; } private: T* _ptr; }; } int main() { return 0; }unique_ptr的模拟实现:
cpp#include<iostream> #include<memory> using namespace std; namespace zx { template<class T> class unique_ptr { public: explicit unique_ptr(T* ptr) :_ptr(ptr) { } ~unique_ptr() { if (_ptr) { cout << "delete" << _ptr << endl; delete _ptr; } } unique_ptr(const unique_ptr<T>& sp) = delete; unique_ptr<T>& operator=(const unique_ptr<T>& sp) = delete; unique_ptr(unique_ptr<T>&& sp) :_ptr(sp._ptr) { sp._ptr = nullptr; } unique_ptr<T>& operator=(unique_ptr<T>&& sp) { if (_ptr) delete _ptr; _ptr = sp._ptr; sp._ptr = nullptr; return *this; } T& operator*() { return *_ptr; } T* operator->() { return _ptr; } private: T* _ptr; }; } int main() { return 0; }1:智能指针不支持从隐式类型转换,所以在默认构造前面增加了一个explicit
2:unique_ptr不支持拷贝构造和赋值,所以将拷贝构造和赋值给delete
3:unique_ptr支持移动构造和移动赋值
4.2 shared_ptr的实现1
- 大家重点要看看shared_ptr是如何设计的,尤其是引用计数的设计,主要这里一份资源就需要一个引用计数,所以引用计数才用静态成员的方式是无法实现的,要使用堆上动态开辟的方式,构造智能指针对象时来一份资源,就要new一个引用计数出来。多个shared_ptr指向资源时就++引用计数,shared_ptr对象析构时就-引用计数,引用计数减到o时代表当前析构的shared_ptr是最后一个管理资源的对象,则析构资源。
cpp#include<iostream> #include<memory> using namespace std; struct Date { Date(int year=1,int month=1,int day=1) :_year(year) ,_month(month) ,_day(day) { } ~Date() { //cout << "~Date()" << endl; } int _year; int _month; int _day; }; namespace zx { template<class T> class shared_ptr { public: shared_ptr(T* ptr) :_ptr(ptr) , _pcount(new int(1)) { } ~shared_ptr() { if ((--*_pcount)==0) { cout << "delete" << _ptr << endl; delete _ptr; delete _pcount; } } shared_ptr(const shared_ptr<T>& sp) :_ptr(sp._ptr) ,_pcount(sp._pcount) { (*_pcount)++; } shared_ptr<T>& operator=(const shared_ptr<T>& sp) { if (_ptr != sp._ptr) { if (--*_pcount == 0) { delete _ptr; delete _pcount; } _ptr = sp._ptr; _pcount = sp._pcount; (*_pcount)++; } return *this; } T& operator*() { return *_ptr; } T* operator->() { return _ptr; } int usecount() { return *_pcount; } private: T* _ptr; int* _pcount; }; } int main() { zx::shared_ptr<Date> sp1 = new Date; zx::shared_ptr<Date> sp2(sp1); zx::shared_ptr<Date> sp3(sp2); zx::shared_ptr<Date> sp4(new Date); cout << sp1.usecount() << endl; cout << sp4.usecount() << endl; sp1->_year++; cout << sp1->_year << "::" << sp2->_year << "::" << sp3->_year << endl; cout << "----------------------------" << endl; //赋值重载 sp1 = sp4; cout << sp1.usecount() << endl; cout << sp4.usecount() << endl; return 0; }1:为什么shared_ptr类里面设计引用计数不能是一个size_t类型的变量,而是需要new一个int资源来充当引用计数?
答:如果使用size_t类型的变量来充当引用计数,现在假如有两个指针sp1和sp2指向同一块资源,sp1和sp2的引用计数都是2,当sp1和sp2都析构时,都只会将sp1和sp2内的引用计数减1,sp1和sp2的引用计数都是1,所以都没有释放资源。所以两个智能指针对象不能各自有一个引用计数,而是需要有一个公共的引用计数。因此需要new一个int资源来充当引用计数。
2:为什么不能用静态成员来实现引用计数呢?
答:静态成员变量属于所有的类对象,所有的智能指针都可以访问这个静态成员变量,无法知道同一个资源被多少智能指针指向。引用计数记录的是一块资源有多少智能指针对象进行管理。
4.3 delete的问题
在上面模拟实现shared_ptr析构函数里面,我们使用的是delete来释放资源,但是如果我们new出来的是数组呢?此时就需要使用delete[]来释放资源,但是我们怎么知道是使用delete还是delete[]呢?
智能指针析构时默认是进行delete释放资源,这也就意味着如果不是new出来的资源,交给智能指针管理,析构时就会崩溃。
代码如下所示:
cpp
#include<iostream>
#include<memory>
using namespace std;
struct Date
{
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
~Date()
{
//cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
int main()
{
shared_ptr<Date> sp1(new Date[10]);
return 0;
}
我们申请了一个Date类型的数组,把这个数组交给智能指针进行管理,当程序结束之后,执行析构函数释放资源会出错,因为我们是new的是数组,释放资源需要使用delete[],不能使用delete。
那底层如何使用delete[]和delete呢?智能指针给了两种方案。
4.3.1 方案一
方案一是一种临时方案,在new一个数组的时候将智能指针的类型设置为Date[],如下所示:
cpp
#include<iostream>
#include<memory>
using namespace std;
struct Date
{
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
~Date()
{
//cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
int main()
{
shared_ptr<Date> sp1(new Date);
shared_ptr<Date[]> sp2(new Date[10]);
return 0;
}
此时运行代码不会崩溃。
new[]经常使用,所以为了简洁一点,unique_ptr和shared_ptr都特化了一份[]的版本,使用时unique_ptr<Date[]> up1(new Date[5]);shared_ptr<Date[]>sp1(new Date[5]);就可以管理new[]的资源。
但是这种方案依旧不能解决fopen的场景,如下所示:
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<memory>
using namespace std;
int main()
{
shared_ptr<FILE> sp1(fopen("test.cpp", "r"));
return 0;
}
此时智能指针管理的资源是fopen打开的文件,我们需要使用fclose来关闭,这就需要使用第二种解决方案,构造时给一个删除器。
4.3.2 方案二
智能指针支持在构造时给一个删除器,所谓删除器本质就是一个可调用对象,这个可调用对象中实现你想要的释放资源的方式,当构造智能指针时,给了定制的删除器,在智能指针析构时就会调用删除器去释放资源。
删除器本质就是一个可调用对象,可以是仿函数,lambda,和函数指针等。
4.3.2.1 仿函数充当删除器
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<memory>
using namespace std;
struct Date
{
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
~Date()
{
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
class Fclose
{
public:
void operator()(FILE* ptr)
{
cout << "fclose:" << ptr << endl;
fclose(ptr);
}
};
class Delete
{
public:
void operator()(Date* ptr)
{
cout << "delete[]" << ptr << endl;
delete[] ptr;
}
};
int main()
{
shared_ptr<FILE> sp1(fopen("test.cpp", "r"),Fclose());
shared_ptr<Date> sp2(new Date);
shared_ptr<Date[]> sp3(new Date[10]); //特化
shared_ptr<Date> sp4(new Date[10], Delete()); //定制删除器
return 0;
}
当程序结束之后,会调用Fclose这个仿函数来释放fopen打开的资源。
4.3.2.2 lambda充当删除器
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<memory>
using namespace std;
struct Date
{
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
~Date()
{
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
int main()
{
shared_ptr<FILE> sp1(fopen("test.cpp", "r"), [](FILE* ptr)
{
cout << "fclose:" << ptr << endl;
fclose(ptr);
});
shared_ptr<Date> sp2(new Date);
shared_ptr<Date> sp3(new Date[10], [](Date* ptr) {delete[] ptr; });
return 0;
}
4.3.2.3 函数指针充当删除器
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<memory>
using namespace std;
struct Date
{
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
~Date()
{
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
template<class T>
void DeleteArrayFunc(T* ptr)
{
cout << "delete[]" << ptr << endl;
delete[] ptr;
}
int main()
{
shared_ptr<Date> sp1(new Date[10], DeleteArrayFunc<Date>);
return 0;
}
4.4 unique_ptr和shared_ptr定制删除器的区别
shared_ptr是在构造函数的时候传入删除器,如下所示:


unique_ptr是在类声明的时候传入删除器,如下所示:


unique_ptr在类声明的时候传入删除器的类型,就会导致只能使用仿函数来充当删除器,因为lambda和函数指针是没有类型的,如下所示:
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<memory>
using namespace std;
class Fclose
{
public:
void operator()(FILE* ptr)
{
cout << "fclose:" << ptr << endl;
fclose(ptr);
}
};
int main()
{
unique_ptr<FILE, Fclose> up1(fopen("test.cpp", "r"));
return 0;
}
如果强行使用lambda就需要使用一下方式:很麻烦
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<memory>
using namespace std;
int main()
{
auto fcloseFunc = [](FILE* ptr) {fclose(ptr); };
unique_ptr<FILE,decltype(fcloseFunc)> up1(fopen("test.cpp", "r"), fcloseFunc);
return 0;
}
综上所述:shared_ptr比unique_ptr好用,使用删除器可以使用仿函数,lambda,和函数指针等,而unique_ptr建议使用仿函数。
4.5 shared_ptr的实现2(删除器)
cpp
#include<iostream>
#include<memory>
#include<functional>
using namespace std;
struct Date
{
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
~Date()
{
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
namespace zx
{
template<class T>
class shared_ptr
{
public:
shared_ptr(T* ptr)
:_ptr(ptr)
, _pcount(new int(1))
{}
template<class D>
shared_ptr(T* ptr,D del)
:_ptr(ptr)
, _pcount(new int(1))
,_del(del)
{}
~shared_ptr()
{
if ((--*_pcount) == 0)
{
cout << "delete" << _ptr << endl;
_del(_ptr);
delete _pcount;
}
}
shared_ptr(const shared_ptr<T>& sp)
:_ptr(sp._ptr)
, _pcount(sp._pcount)
{
(*_pcount)++;
}
shared_ptr<T>& operator=(const shared_ptr<T>& sp)
{
if (_ptr != sp._ptr)
{
if (--*_pcount == 0)
{
delete _ptr;
delete _pcount;
}
_ptr = sp._ptr;
_pcount = sp._pcount;
(*_pcount)++;
}
return *this;
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
int usecount()
{
return *_pcount;
}
private:
T* _ptr;
int* _pcount;
function<void(T*)> _del= [](Date* ptr) {delete ptr; };
};
}
int main()
{
zx::shared_ptr<Date> sp1(new Date);
zx::shared_ptr<Date> sp2(new Date[10], [](Date* ptr) {delete[] ptr; });
return 0;
}
五、shared_ptr和weak_ptr
5.1 shared_ptr循环引用问题
- shared_ptr大多数情况下管理资源非常合适,支持RAll,也支持拷贝。但是在循环引用的场景下会导致资源没得到释放内存泄漏,所以我们要认识循环引用的场景和资源没释放的原因,并且学会使用weak_ptr解决这种问题。
- 如下图所述场景,n1和n2析构后,管理两个节点的引用计数减到1
- 右边的节点什么时候释放呢,左边节点中的_next管着呢,_next析构后,右边的节点就释放了。
- _next什么时候析构呢,_next是左边节点的的成员,左边节点释放,_next就析构了。
- 左边节点什么时候释放呢,左边节点由右边节点中的_prev管着呢,_prev析构后,左边的节点就释放了。
- _prev什么时候析构呢,_prev是右边节点的成员,右边节点释放,_prev就析构了。
代码如下所示:
cpp#include<iostream> #include<memory> using namespace std; struct ListNode { int _data; ListNode* _next; ListNode* _prev; ~ListNode() { cout << "~ListNode()" << endl; } }; int main() { std::shared_ptr<ListNode> n1(new ListNode); std::shared_ptr<ListNode> n2(new ListNode); return 0; }此时运行程序没有什么问题,但是如果想要让n1的next指向n2,n2的prev指向n1.就会出问题。如下所示:
cpp#include<iostream> #include<memory> using namespace std; struct ListNode { int _data; ListNode* _next; ListNode* _prev; ~ListNode() { cout << "~ListNode()" << endl; } }; int main() { std::shared_ptr<ListNode> n1(new ListNode); std::shared_ptr<ListNode> n2(new ListNode); n1->_next = n2; n2->_prev = n1; return 0; }运行之后会发生如下的错误:
这是因为n2是std::shared_ptr<ListNode>类型,而n1->_next是ListNode*类型,一个智能指针类型怎么能给原生指针呢?所以需要将ListNode里面的指针也需要改成智能指针,如下所示:
cpp#include<iostream> #include<memory> using namespace std; struct ListNode { int _data; /*ListNode* _next; ListNode* _prev;*/ std::shared_ptr<ListNode> _next; std::shared_ptr<ListNode> _prev; ~ListNode() { cout << "~ListNode()" << endl; } }; int main() { std::shared_ptr<ListNode> n1(new ListNode); std::shared_ptr<ListNode> n2(new ListNode); n1->_next = n2; n2->_prev = n1; return 0; }此时n1和n2相互引用之后就会导致循环引用,当程序结束之后,两个节点都没有释放!!!如下图所示:
- 至此逻辑上成功形成回旋镖似的循环引用,谁都不会释放就形成了循环引用,导致内存泄漏
- **把ListNode结构体中的_next和_prev改成weak_ptr,weak_ptr绑定到shared_ptr时不会增加它的引用计数,_next和_prev不参与资源释放管理逻辑,就成功打破了循环引用,解决了这里的问题,**如下。
5.2 weak_ptr
weak_ptr构造函数如下:

它支持默认的无参构造,支持拷贝构造,支持使用shared_ptr来构造和赋值。
- weak_ptr不支持RAll,也不支持访问资源,所以我们看文档发现weak_ptr构造时不支持绑定到资源,只支持绑定到shared_ptr,绑定到shared_ptr时,不增加shared_ptr的引用计数,那么就可以解决上述的循环引用问题。
- weak_ptr也没有重载operator*和operator->等,因为他不参与资源管理,那么如果他绑定的shared_ptr已经释放了资源,那么他去访问资源就是很危险的。weakptr支持expired检查指向的资源是否过期,use_count也可获取shared_ptr的引l用计数,weak_ptr想访问资源时,可以调用lock返回一个管理资源的shared_ptr,如果资源已经被释放,返回的shared_ptr是一个空对象,如果资源没有释放,则通过返回的shared_ptr访问资源是安全的。
cpp
#include<iostream>
#include<memory>
using namespace std;
struct ListNode
{
int _data;
/*ListNode* _next;
ListNode* _prev;*/
/*std::shared_ptr<ListNode> _next;
std::shared_ptr<ListNode> _prev;*/
//这里改成weak_ptr,当nl->next=n2;绑定shared_ptr时
// 不增加n2的引用计数,不参与资源释放的管理,就不会形成循环引用了
std::weak_ptr<ListNode> _next;
std::weak_ptr<ListNode> _prev;
~ListNode()
{
cout << "~ListNode()" << endl;
}
};
int main()
{
std::shared_ptr<ListNode> n1(new ListNode);
std::shared_ptr<ListNode> n2(new ListNode);
n1->_next = n2;
n2->_prev = n1;
return 0;
}
weak_ptr的方法使用如下所示:
cpp
#include<iostream>
#include<memory>
using namespace std;
int main()
{
std::shared_ptr<string> sp1(new string("111111"));
std::shared_ptr<string> sp2(sp1);
std::weak_ptr<string> wp = sp1;
cout << wp.expired() << endl;
cout << wp.use_count() << endl;
// sp1和sp2都指向了其他资源,则weak_ptr就过期了
sp1 = make_shared<string>("222222");
cout << wp.expired() << endl;
cout << wp.use_count() << endl;
sp2 = make_shared<string>("333333");
cout << wp.expired() << endl;
cout << wp.use_count() << endl;
wp = sp1;
//std::shared_ptr<string> sp3 = wp.lock();
auto sp3 = wp.lock();
cout << wp.expired() << endl;
cout << wp.use_count() << endl;
*sp3 += "###";
cout << *sp1 << endl;
return 0;
}
六、shared_ptr的线程安全问题
- shared_ptr的引用计数对象在堆上,如果多个shared_ptr对象在多个线程中,进行shared_ptr的拷贝析构时会访问修改引用计数,就会存在线程安全问题,所以shared_ptr引用计数是需要加锁或者原子操作保证线程安全的。
- shared_ptr指向的对象也是有线程安全的问题的,但是这个对象的线程安全问题不归shared_ptr管,它也管不了,应该有外层使用shared_ptr的人进行线程安全的控制。
七、C++11和boost中智能指针的关系
- Boost库是为C++语言标准库提供扩展的一些C++程序库的总称,Boost社区建立的初衷之一就是为C++的标准化工作提供可供参考的实现,Boost社区的发起人Dawes本人就是C++标准委员会的成员之一。在Boost库的开发中,Boost社区也在这个方向上取得了丰硕的成果,C++11及之后的新语法和库有很多都是从Boost中来的。
- C++ 98 中产生了第一个智能指针auto_ptr。
- C++ boost给出了更实用的scoped_ptr/scoped_array和shared_ptr/shared_array和weak_ptr等.
- C++TR1,引入了shared_ptr等,不过注意的是TR1并不是标准版。
- C++11,引入了unique_ptr和shared_ptr和weak_ptr。需要注意的是unique_ptr对应boost的scoped_ptr。并且这些智能指针的实现原理是参考boost中的实现的。
八、内存泄漏
8.1 什么是内存泄漏,内存泄漏的危害
什么是内存泄漏:内存泄漏指因为疏忽或错误造成程序未能释放已经不再使用的内存,一般是忘记释放或者发生异常释放程序未能执行导致的。内存泄漏并不是指内存在物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费。
内存泄漏的危害:普通程序运行一会就结束了出现内存泄漏问题也不大,进程正常结束,页表的映射关系解除,物理内存也可以释放。长期运行的程序出现内存泄漏,影响很大,如操作系统、后台服务、长时间运行的客户端等等,不断出现内存泄漏会导致可用内存不断变少,各种功能响应越来越慢,最终卡死。
int main ()
{
// 申请⼀个 1G 未释放,这个程序多次运⾏也没啥危害
// 因为程序⻢上就结束,进程结束各种资源也就回收了
char * ptr = new char [ 1024 * 1024 * 1024 ];
cout << ( void *)ptr << endl;
return 0 ;
}
8.2 如何检测内存泄漏
linux下内存泄漏检测:Linux下几款C++程序中的内存泄露检查工具_c++内存泄露工具分析-CSDN博客
windows下使用第三方工具:windows下的内存泄露检测工具VLD使用_windows内存泄漏检测工具-CSDN博客
8.3 如何避免内存泄漏
- 工程前期良好的设计规范,养成良好的编码规范,申请的内存空间记着匹配的去释放。ps:这个理想状态。但是如果碰上异常时,就算注意释放了,还是可能会出问题。需要下一条智能指针来管理才有保证。
- 尽量使用智能指针来管理资源,如果自己场景比较特殊,采用RAII思想自己造个轮子管理。
- 定期使用内存泄漏工具检测,尤其是每次项目快上线前,不过有些工具不够靠谱,或者是收费。
- 总结一下:内存泄漏非常常见,解决方案分为两种:1、事前预防型。如智能指针等。2、事后查错型。如泄漏检测工具。





