目录
下面我们先分析一下下面这段程序有没有什么内存方面的问题?提示一下:注意分析Func函数中的问题。
- int div()
- {
- int a, b;
- cin >> a >> b;
- if (b == 0)
- throw invalid_argument("除0错误");
- return a / b;
- }
- void Func()
- {
- // 1、如果p1这里new 抛异常会如何?
- // 2、如果p2这里new 抛异常会如何?
- // 3、如果div调用这里又会抛异常会如何?
- int* p1 = new int;
- int* p2 = new int;
- cout << div() << endl;
- delete p1;
- delete p2;
- }
- int main()
- {
- try
- {
- Func();
- }
- catch (exception& e)
- {
- cout << e.what() << endl;
- }
- return 0;
- }
说明:
什么是内存泄漏,内存泄漏的危害:
什么是内存泄漏:内存泄漏指因为疏忽或错误造成程序未能释放已经不再使用的内存的情况。内
存泄漏并不是指内存在物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对
该段内存的控制,因而造成了内存的浪费。
内存泄漏的危害:长期运行的程序出现内存泄漏,影响很大,如操作系统、后台服务等等,出现
内存泄漏会导致响应越来越慢,最终卡死。
内存泄漏分类:
C/C++程序中一般我们关心两种方面的内存泄漏:
1.堆内存泄漏(Heap leak):
2.系统资源泄漏:
如何避免内存泄漏:
总结一下:
内存泄漏非常常见,解决方案分为两种:1、事前预防型。如智能指针等。2、事后查错型。如泄
漏检测工具
RAII(Resource Acquisition Is Initialization)是一种利用对象生命周期来控制程序资源(如内
存、文件句柄、网络连接、互斥量等等)的简单技术。
在对象构造时获取资源,接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在
对象析构的时候释放资源。借此,我们实际上把管理一份资源的责任托管给了一个对象。这种做
法有两大好处:
设计简单的RAII智能指针:
- template<class T>
- class smart_ptr
- {
- public:
- smart_ptr(T *ptr)
- :_ptr(ptr)
- {
- }
-
- ~smart_ptr()
- {
- cout << "delete _ptr" << endl;
- delete _ptr;
- }
-
- private:
- T* _ptr;
- };
-
- int div()
- {
- int a, b;
- cin >> a >> b;
- if (b == 0)
- throw invalid_argument("除0错误");
- return a / b;
- }
- void Func()
- {
- smart_ptr<int>p1( new int);
- smart_ptr<int>p2(new int);
- cout << div() << endl;
- }
- int main()
- {
- try
- {
- Func();
- }
- catch (exception& e)
- {
- cout << e.what() << endl;
- }
- return 0;
- }
测试结果:
上述的 smart_ptr 还不能将其称为智能指针,因为它还不具有指针的行为。指针可以解引用,也可
以通过->去访问所指空间中的内容,因此:AutoPtr模板类中还得需要将* 、->重载下,才可让其
像指针一样去使用。
- template<class T>
- class smart_ptr
- {
- public:
- smart_ptr(T *ptr)
- :_ptr(ptr)
- {
- }
-
- T& operator*() { return *_ptr; }
- T* operator->() { return _ptr; }
-
- ~smart_ptr()
- {
- cout << "delete _ptr" << endl;
- if(_ptr)
- delete _ptr;
- }
- private:
- T* _ptr;
- };
-
- struct Date
- {
- int _year;
- int _month;
- int _day;
- };
-
- int main()
- {
- smart_ptr<int> sp1(new int);
- *sp1 = 10;
- cout << *sp1 << endl;
- smart_ptr
sparray(new Date) ; - // 需要注意的是这里应该是sparray.operator->()->_year = 2018;
- // 本来应该是sparray->->_year这里语法上为了可读性,省略了一个->
- sparray->_year = 2018;
- sparray->_month = 1;
- sparray->_day = 1;
-
- cout << sparray->_year << ":" << sparray->_month << ":" << sparray->_day << endl;
- return 0;
- }
总结一下智能指针的原理:
C++98版本的库中就提供了auto_ptr的智能指针。下面演示的auto_ptr的使用及问题。
auto_ptr的实现原理:管理权转移的思想,下面简化模拟实现了一份bit::auto_ptr来了解它的原
理。
- template<class T>
- class myatuo_ptr
- {
- public:
- myatuo_ptr(T* ptr)
- :_ptr(ptr)
- {
- }
-
- //像指针一样访问
- T& operator*() { return *_ptr; }
- T* operator->() { return _ptr; }
-
-
- //管理权转移,一次只能有一个对象管理资源
- myatuo_ptr& operator=(myatuo_ptr& ptr)
- {
- //不是自己给自己赋值
- if (this != &ptr)
- {
- //1.先释放当前管理的资源
- if (_ptr)
- {
- delete _ptr;
- }
- //2.转移管理权
- _ptr = ptr._ptr;
- ptr._ptr = nullptr;
- }
- return *this;
- }
-
- ~myatuo_ptr()
- {
- cout << "delete _ptr" << endl;
- if (_ptr)
- delete _ptr;
- }
-
- private:
- T* _ptr;
- };
-
-
- int main()
- {
- ikun::myatuo_ptr<int> pint(new int);
- *pint = 100;
- ikun::myatuo_ptr<int> pint1(new int);
- pint1 = pint;
- cout << *pint1 << endl;
-
- return 0;
-
- }
致命缺点:指针悬空
结论:auto_ptr是一个失败设计,很多公司明确要求不能使用auto_ptr。
C++11中开始提供更靠谱的unique_ptr。
unique_ptr的实现原理:简单粗暴的防拷贝,下面简化模拟实现了一份UniquePtr来了解它的原
理。
- template<class T>
- class myunique_ptr
- {
- public:
- myunique_ptr(T* ptr)
- :_ptr(ptr)
- {
- }
-
- //像指针一样访问
- T& operator*() { return *_ptr; }
- T* operator->() { return _ptr; }
-
- //强制不生成赋值运算符和拷贝构造
- myunique_ptr& operator=(myunique_ptr& ptr) = delete;
- myunique_ptr(myunique_ptr& ptr) = delete;
-
-
- ~myunique_ptr()
- {
- cout << "delete _ptr" << endl;
- if (_ptr)
- delete _ptr;
- }
-
- private:
- T* _ptr;
- };
C++11中开始提供更靠谱的并且支持拷贝的shared_ptr。
shared_ptr的原理:是通过引用计数的方式来实现多个shared_ptr对象之间共享资源。
原理:
实现原理:
- template<class T>
- class myshare_ptr
- {
- public:
- myshare_ptr(T* ptr=nullptr)
- :_ptr(ptr),
- _pcount(new int(1)),
- {
- }
-
- //像指针一样访问
- T& operator*() { return *_ptr; }
- T* operator->() { return _ptr; }
-
- //拷贝构造
- myshare_ptr(myshare_ptr& ptr)
- :_ptr(ptr._ptr),
- _pcount(ptr._pcount),
- {
- addref();
- }
-
- //赋值重载运算符
- myshare_ptr& operator=(myshare_ptr& ptr)
- {
- //this!=&ptr
- if (_ptr != ptr._ptr)
- {
- release();
- _ptr = ptr._ptr;
- _pcount = ptr._pcount;
- ptr.addref();
- }
- }
-
- ~myshare_ptr()
- {
- release();
- }
-
- private:
- //对引用计数的++
- void addref()
- {
- (*_pcount)++;
- }
- //对引用计数的--
- void release()
- {
- (*_pcount)--;
- if ((*_pcount) == 0)
- {
- if (_ptr)
- {
- delete _ptr;
- delete _pcount;
- cout << "delete _ptr" << endl;
- }
- }
- }
-
- private:
- T* _ptr;
- int* _pcount;
- };
- }
需要注意的是shared_ptr的线程安全分为两方面:
所以我们需要对上述代码的引用计数的操作进行加锁保护:
- template<class T>
- class myshare_ptr
- {
- public:
- myshare_ptr(T* ptr=nullptr)
- :_ptr(ptr),
- _pcount(new int(1)),
- _mutex(new mutex)
- {
- }
-
- //像指针一样访问
- T& operator*() { return *_ptr; }
- T* operator->() { return _ptr; }
-
- //拷贝构造
- myshare_ptr(myshare_ptr& ptr)
- :_ptr(ptr._ptr),
- _pcount(ptr._pcount),
- _mutex(ptr._mutex)
- {
- addref();
- }
-
- //赋值重载运算符
- myshare_ptr& operator=(myshare_ptr& ptr)
- {
- //this!=&ptr
- if (_ptr != ptr._ptr)
- {
- release();
- _ptr = ptr._ptr;
- _pcount = ptr._pcount;
- _mutex = ptr._mutex;
- ptr.addref();
- }
- return *this;
- }
-
- ~myshare_ptr()
- {
- release();
- }
-
- private:
- //对引用计数的++
- void addref()
- {
- _mutex->lock();//加锁
- (*_pcount)++;
- _mutex->unlock();
- }
- //对引用计数的--
- void release()
- {
- _mutex->lock();//加锁
- (*_pcount)--;
- if ((*_pcount) == 0)
- {
- if (_ptr)
- {
- delete _ptr;
- delete _pcount;
- deletemutex = 1;
- }
- }
- _mutex->unlock();
- if (deletemutex)
- {
- delete _mutex;
- }
- }
-
- }
-
- private:
- T* _ptr;
- int* _pcount;
- mutex* _mutex;
- };
shared_ptr在一些特殊的场景下也会有bug,例如下列代码:
- struct ListNode
- {
- int _data;
- shared_ptr
_prev; - shared_ptr
_next; - ~ListNode() { cout << "~ListNode()" << endl; }
- };
-
- int main()
- {
- shared_ptr
n1(new ListNode) ; - shared_ptr
n2(new ListNode) ; - n1->_next = n2;
- n2->_prev = n1;
-
- return 0;
- }
循环引用分析:
解决方案:在引用计数的场景下,把节点中的_prev和_next改成weak_ptr就可以了。
原理就是,node1->_next = node2;和node2->_prev = node1;时weak_ptr的_next和_prev不会增加node1和node2的引用计数。
weak_ptr实现原理:
- template<class T>
- class myweak_ptr
- {
- public:
- myweak_ptr()
- :_ptr(nullptr)
- {}
-
- myweak_ptr(const shared_ptr
& sp) - :_ptr(sp.get())
- {}
-
- T& operator*()
- {
- return *_ptr;
- }
-
- T* operator->()
- {
- return _ptr;
- }
-
- T* get()
- {
- return _ptr;
- }
-
- private:
- T* _ptr;
- };
解决循环引用:
- struct ListNode
- {
- int _data;
- weak_ptr
_prev; - weak_ptr
_next; - ~ListNode() { cout << "~ListNode()" << endl; }
- };
-
- int main()
- {
- shared_ptr
n1(new ListNode) ; - shared_ptr
n2(new ListNode) ; - n1->_next = n2;
- n2->_prev = n1;
- return 0;
- }
如果不是new出来的对象如何通过智能指针管理呢?有可能是,malloc出来的,或者是一个文件指针,又该如何处理呢,其实shared_ptr设计了一个删除器来解决这个问题。
删除器:是一个可调用对象,让我们根据我们管理的指针的类型,来设计特定的释放函数,防止释放混乱,将可调用在构造时传智能指针。可调用对象可以是,函数指针,lambda,函数对象,仿函数。
例如:
- template<class T>
- struct deletedate
- {
- void operator()(T*ptr)
- {
- cout << "delete[] ptr" << endl;
- delete[] ptr;
- }
- };
-
- template<class T>
- void deletemalloc(T* ptr)
- {
- cout << "free (ptr)" << endl;
- free(ptr);
- }
-
- int main()
- {
- //lambda
- shared_ptr
ptr(fopen("test.c", "w+"), [](FILE* fptr) {fclose(fptr); cout << "fclose(fptr)" << endl; }) ; - //函数指针
- shared_ptr<int> ptr1((int*)malloc(4),deletemalloc<int>);
- //仿函数
- shared_ptr<int> ptr2(new int[10], deletedate<int>());
- //函数对象
- shared_ptr<int> ptr3((int*)malloc(sizeof(int)*10), function<void(int*)>(deletemalloc<int>));
-
- return 0;
- }
实现原理:
- template<class T>
- class myshare_ptr
- {
- public:
- myshare_ptr(T* ptr=nullptr)
- :_ptr(ptr),
- _pcount(new int(1)),
- _mutex(new mutex)
- {
- }
-
- myshare_ptr(T* ptr, function<void(T*)> func_delete)
- :_ptr(ptr),
- _pcount(new int(1)),
- _mutex(new mutex),
- _func_delete(func_delete)
- {
- }
-
- //像指针一样访问
- T& operator*() { return *_ptr; }
- T* operator->() { return _ptr; }
-
- //拷贝构造
- myshare_ptr(myshare_ptr& ptr)
- :_ptr(ptr._ptr),
- _pcount(ptr._pcount),
- _mutex(ptr._mutex),
- _func_delete(ptr._func_delete)
- {
- addref();
- }
-
- //赋值重载运算符
- myshare_ptr& operator=(myshare_ptr& ptr)
- {
- //this!=&ptr
- if (_ptr != ptr._ptr)
- {
- release();
- _ptr = ptr._ptr;
- _pcount = ptr._pcount;
- _mutex = ptr._mutex;
- _func_delete = ptr._func_delete;
- ptr.addref();
- }
- return *this;
- }
-
- ~myshare_ptr()
- {
- release();
- }
-
- private:
- //对引用计数的++
- void addref()
- {
- _mutex->lock();
- (*_pcount)++;
- _mutex->unlock();
- }
- //对引用计数的--
- void release()
- {
- _mutex->lock();
- (*_pcount)--;
- bool deletemutex = 0;
- if ((*_pcount) == 0)
- {
- if (_ptr)
- {
- _func_delete(_ptr);
- delete _pcount;
- deletemutex = 1;
- }
- }
- _mutex->unlock();
- if (deletemutex)
- {
- delete _mutex;
- }
- }
-
- private:
- T* _ptr;
- int* _pcount;
- mutex* _mutex;
- function<void(T*)> _func_delete = [](T* ptr) {delete ptr};//默认释放
- };