赞
踩
目录
先分析下面这段程序有没有什么内存方面的问题?
- #define _CRT_SECURE_NO_WARNINGS 1
-
- #include <iostream>
- using namespace std;
-
- 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;
- }

什么是内存泄漏:内存泄漏是指因为疏忽或者错误造成程序未能释放已经不再使用的内存的情况。内存泄漏并不是指内存在物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费。
内存泄漏的危害:长期运行的程序出现内存泄漏,影响很大,如操作系统、后台服务等等,出现内存泄漏会导致响应越来越慢,最终卡死。
- void MemoryLeaks()
- {
- // 1.内存申请了忘记释放
- int* p1 = (int*)malloc(sizeof(int));
- int* p2 = new int;
-
- // 2.异常安全问题
- int* p3 = new int[10];
-
- Func(); // 这里Func函数抛异常导致 delete[] p3未执行,p3没被释放.
-
- delete[] p3;
- }
C/C++程序中一般关心两种方面的内存泄漏:
堆内存指的是程序执行中依据须要分配通过malloc/calloc/realloc/new等从堆中分配的一块内存,用完后必须通过调用相应的free或者delete删掉。假设程序的设计错误导致这部分内存没有被释放,那么以后这部分空间将无法再次被使用,就会产生Heap Leak。
指程序使用系统分配的资源,比如套接字、文件描述符、管道等没有使用对应的函数释放掉,导致系统资源的浪费,严重可导致系统效能减少,系统执行不稳定。
总结:
内存泄漏非常常见,解决方案分为两种:
RAII(Resource Acquisition Is Initialization)是一种利用对象生命周期来控制程序资源(如内存、文件句柄、网络连接、互斥量等等)的简单技术。
在对象构造时获取资源,接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在对象析构的时候释放资源。借此,实际上把管理一份资源的责任托管给了一个对象。这种做法有两大好处:
- // 使用RAII思想设计的SmartPtr类
- template<class T>
- class SmartPtr {
- public:
- SmartPtr(T* ptr = nullptr)
- : _ptr(ptr)
- {}
- ~SmartPtr()
- {
- if (_ptr)
- 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()
- {
- SmartPtr<int> sp1(new int);
- SmartPtr<int> sp2(new int);
-
- cout << div() << endl;
- }
-
- int main()
- {
- try
- {
- Func();
- }
- catch (const exception& e)
- {
- cout << e.what() << endl;
- }
- return 0;
- }

上述的SmartPtr还不能将其称为智能指针,因为它还不具有指针的行为。指针可以解引用,也可以通过->去访问所指空间中的内容,因此:AutoPtr模板类中还需要将*、->重载下,才可以让其像指针一样去使用。
- template<class T>
- class SmartPtr {
- public:
- SmartPtr(T* ptr = nullptr)
- : _ptr(ptr)
- {}
- ~SmartPtr()
- {
- if (_ptr)
- delete _ptr;
- }
-
- T& operator*() { return *_ptr; }
- T* operator->() { return _ptr; }
-
- private:
- T* _ptr;
- };
-
- struct Date
- {
- int _year;
- int _month;
- int _day;
- };
-
- int main()
- {
- SmartPtr<int> sp1(new int);
- *sp1 = 10;
-
- cout << *sp1 << endl;
-
- SmartPtr<Date> sparray(new Date);
-
- // 需要注意的是这里应该是sparray.operator->()->_year = 2018;
- // 本来应该是sparray->->_year这里语法上为了可读性,省略了一个->
- sparray->_year = 2018;
- sparray->_month = 1;
- sparray->_day = 1;
- }

总结一下智能指针的原理:
C++98版本的库中就提供了auto_ptr的智能指针。下面演示auto_ptr的使用及问题。
auto_ptr的实现原理:管理权转移的思想,下面简化模拟实现了一份fyd::auto_ptr来了解它的原理。
- // C++98 管理权转移 auto_ptr
- namespace fyd
- {
- 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;
-
- // 转移ap中资源到当前对象中
- _ptr = ap._ptr;
- ap._ptr = NULL;
- }
- 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()
- //{
- // std::auto_ptr<int> sp1(new int);
- // std::auto_ptr<int> sp2(sp1); // 管理权转移
- //
- // // sp1悬空
- // *sp2 = 10;
- // cout << *sp2 << endl;
- // cout << *sp1 << endl;
- //
- // return 0;
- //}

结论:auto_ptr是一个失败的设计,很多公司明确要求不能使用auto_ptr。
C++11中开始提供更靠谱的unique_ptr。
unique_ptr的实现原理:简单粗暴的防拷贝,下面简化实现了一份fyd::unique_ptr来了解它的原理。
- // C++11库才更新智能指针实现
- // C++11出来之前,boost搞除了更好用的scoped_ptr/shared_ptr/weak_ptr
- // C++11将boost库中智能指针精华部分吸收了过来
- // C++11->unique_ptr/shared_ptr/weak_ptr
- // unique_ptr/scoped_ptr
- // 原理:简单粗暴 -- 防拷贝
- namespace fyd
- {
- template<class T>
- class unique_ptr
- {
- public:
- unique_ptr(T* ptr)
- :_ptr(ptr)
- {}
-
- ~unique_ptr()
- {
- if (_ptr)
- {
- cout << "delete:" << _ptr << endl;
- delete _ptr;
- }
- }
-
- // 像指针一样使用
- T& operator*()
- {
- return *_ptr;
- }
-
- T* operator->()
- {
- return _ptr;
- }
-
- unique_ptr(const unique_ptr<T>&sp) = delete;
- unique_ptr<T>& operator=(const unique_ptr<T>&sp) = delete;
-
- private:
- T* _ptr;
- };
- }
-
- //int main()
- //{
- // fyd::unique_ptr<int> sp1(new int);
- // fyd::unique_ptr<int> sp2(sp1);
- //
- // std::unique_ptr<int> sp1(new int);
- // std::unique_ptr<int> sp2(sp1);
- //
- // return 0;
- //}

C++11中开始提供更靠谱的并且支持拷贝的shared_ptr。
shared_ptr的原理:通过引用计数的方式来实现多个shared_ptr对象之间共享资源。
- // 引用计数支持多个拷贝管理同一个资源,最后一个析构对象释放资源
- namespace fyd
- {
- template<class T>
- class shared_ptr
- {
- public:
- shared_ptr(T* ptr = nullptr)
- :_ptr(ptr)
- , _pRefCount(new int(1))
- , _pmtx(new mutex)
- {}
- shared_ptr(const shared_ptr<T>& sp)
- :_ptr(sp._ptr)
- , _pRefCount(sp._pRefCount)
- , _pmtx(sp._pmtx)
- {
- AddRef();
- }
-
- void Release()
- {
- _pmtx->lock();
- bool flag = false;
- if (--(*_pRefCount) == 0 && _ptr)
- {
- cout << "delete:" << _ptr << endl;
- delete _ptr;
- delete _pRefCount;
- flag = true;
- }
- _pmtx->unlock();
- if (flag == true)
- {
- delete _pmtx;
- }
- }
-
- void AddRef()
- {
- _pmtx->lock();
- ++(*_pRefCount);
- _pmtx->unlock();
- }
-
- shared_ptr<T>& operator=(const shared_ptr<T>& sp)
- {
- //if (this != &sp)
- if (_ptr != sp._ptr)
- {
- Release();
- _ptr = sp._ptr;
- _pRefCount = sp._pRefCount;
- _pmtx = sp._pmtx;
- AddRef();
- }
-
- return *this;
- }
-
- int use_count()
- {
- return *_pRefCount;
- }
-
- ~shared_ptr()
- {
- Release();
- }
-
- // 像指针一样使用
- T& operator*()
- {
- return *_ptr;
- }
-
- T* operator->()
- {
- return _ptr;
- }
-
- T* get() const
- {
- return _ptr;
- }
-
- private:
- T* _ptr;
- int* _pRefCount;
- mutex* _pmtx;
- };
-
- // 简化版本的weak_ptr实现
- template<class T>
- class weak_ptr
- {
- public:
- weak_ptr()
- :_ptr(nullptr)
- {}
- weak_ptr(const shared_ptr<T>& sp)
- :_ptr(sp.get())
- {}
-
- weak_ptr<T>& operator=(const shared_ptr<T>& sp)
- {
- _ptr = sp.get();
- return *this;
- }
-
- T& operator*()
- {
- return *_ptr;
- }
-
- T* operator->()
- {
- return _ptr;
- }
-
- private:
- T* _ptr;
- };
- }
- // shared_ptr智能指针是线程安全的吗?
- // 是的,引用计数的加减是加锁保护的。但是指向资源不是线程安全的
- // 指向堆上资源的线程安全问题是访问的人处理的,智能指针不管,也管不了
- // 引用计数的线程安全问题,是智能指针要处理的
- //int main()
- //{
- // fyd::shared_ptr<int> sp1(new int);
- // fyd::shared_ptr<int> sp2(sp1);
- // fyd::shared_ptr<int> sp3(sp1);
- //
- // fyd::shared_ptr<int> sp4(new int);
- // fyd::shared_ptr<int> sp5(sp4);
- //
- // sp1 = sp1;
- // sp1 = sp2;
- //
- // sp1 = sp4;
- // sp2 = sp4;
- // sp3 = sp4;
- //
- // *sp1 = 2;
- // *sp2 = 3;
- //
- // return 0;
- //}

std::shared_ptr的线程安全问题
通过下面的程序可以测试shared_ptr的线程安全问题。需要注意的是shared_ptr的线程安全分为两个方面:
- // 1.演示引用计数线程安全问题,就把AddRefCount和SubRefCount中的锁去掉
- // 2.演示可能不出现线程安全问题,因为线程安全问题是偶现性问题,main函数的n改大一些概率就变大了,就容易出现了。
- // 3.下面代码我们使用SharedPtr演示,是为了方便演示引用计数的线程安全问题,
- // 将代码中的SharedPtr换成shared_ptr进行测试,可以验证库的shared_ptr,发现结论是一样的。
- namespace fyd
- {
- template<class T>
- class shared_ptr
- {
- public:
- shared_ptr(T* ptr = nullptr)
- :_ptr(ptr)
- , _pRefCount(new int(1))
- , _pmtx(new mutex)
- {}
- shared_ptr(const shared_ptr<T>& sp)
- :_ptr(sp._ptr)
- , _pRefCount(sp._pRefCount)
- , _pmtx(sp._pmtx)
- {
- AddRef();
- }
-
- void Release()
- {
- _pmtx->lock();
- bool flag = false;
- if (--(*_pRefCount) == 0 && _ptr)
- {
- cout << "delete:" << _ptr << endl;
- delete _ptr;
- delete _pRefCount;
- flag = true;
- }
- _pmtx->unlock();
- if (flag == true)
- {
- delete _pmtx;
- }
- }
-
- void AddRef()
- {
- _pmtx->lock();
- ++(*_pRefCount);
- _pmtx->unlock();
- }
-
- shared_ptr<T>& operator=(const shared_ptr<T>& sp)
- {
- //if (this != &sp)
- if (_ptr != sp._ptr)
- {
- Release();
- _ptr = sp._ptr;
- _pRefCount = sp._pRefCount;
- _pmtx = sp._pmtx;
- AddRef();
- }
-
- return *this;
- }
-
- int use_count()
- {
- return *_pRefCount;
- }
-
- ~shared_ptr()
- {
- Release();
- }
-
- // 像指针一样使用
- T& operator*()
- {
- return *_ptr;
- }
-
- T* operator->()
- {
- return _ptr;
- }
-
- T* get() const
- {
- return _ptr;
- }
-
- private:
- T* _ptr;
- int* _pRefCount;
- mutex* _pmtx;
- };
-
- // 简化版本的weak_ptr实现
- template<class T>
- class weak_ptr
- {
- public:
- weak_ptr()
- :_ptr(nullptr)
- {}
- weak_ptr(const shared_ptr<T>& sp)
- :_ptr(sp.get())
- {}
-
- weak_ptr<T>& operator=(const shared_ptr<T>& sp)
- {
- _ptr = sp.get();
- return *this;
- }
-
- T& operator*()
- {
- return *_ptr;
- }
-
- T* operator->()
- {
- return _ptr;
- }
-
- private:
- T* _ptr;
- };
- }
-
- struct Date
- {
- int _year = 0;
- int _month = 0;
- int _day = 0;
- };
-
- void SharePtrFunc(fyd::shared_ptr<Date>& sp, size_t n, mutex& mtx)
- {
- cout << sp.get() << endl;
- for (size_t i = 0; i < n; ++i)
- {
- // 这里智能指针拷贝会++计数,智能指针析构会--计数,这里是线程安全的。
- fyd::shared_ptr<Date> copy(sp);
- // 这里智能指针访问管理的资源,不是线程安全的。
- // 所以我们看看这些值两个线程++了2n次,但是最终看到的结果,并一定是加了2n
- {
- unique_lock<mutex> lk(mtx);
- copy->_year++;
- copy->_month++;
- copy->_day++;
- }
- }
- }
-
- int main()
- {
- fyd::shared_ptr<Date> p(new Date);
-
- cout << p.get() << endl;
-
- const size_t n = 100000;
- mutex mtx;
-
- thread t1(SharePtrFunc, std::ref(p), n, std::ref(mtx));
- thread t2(SharePtrFunc, std::ref(p), n, std::ref(mtx));
-
- t1.join();
- t2.join();
-
- cout << p->_year << endl;
- cout << p->_month << endl;
- cout << p->_day << endl;
- cout << p.use_count() << endl;
-
- return 0;
- }

std::shared_ptr的循环引用
- struct ListNode
- {
- int _data;
-
- shared_ptr<ListNode> _prev;
- shared_ptr<ListNode> _next;
-
- ~ListNode() { cout << "~ListNode()" << endl; }
- };
-
- int main()
- {
- shared_ptr<ListNode> node1(new ListNode);
- shared_ptr<ListNode> node2(new ListNode);
-
- cout << node1.use_count() << endl;
- cout << node2.use_count() << endl;
-
- node1->_next = node2;
- node2->_prev = node1;
-
- cout << node1.use_count() << endl;
- cout << node2.use_count() << endl;
-
- return 0;
- }

循环引用分析:
- // 解决方案:在引用计数的场景下,把节点中的_prev和_next改成weak_ptr就可以了
- // 原理就是,node1->_next = node2;和node2->_prev = node1;时
- // weak_ptr的_next和_prev不会增加node1和node2的引用计数。
- struct ListNode
- {
- int _data;
-
- weak_ptr<ListNode> _prev;
- weak_ptr<ListNode> _next;
-
- ~ListNode() { cout << "~ListNode()" << endl; }
- };
-
- int main()
- {
- shared_ptr<ListNode> node1(new ListNode);
- shared_ptr<ListNode> node2(new ListNode);
-
- cout << node1.use_count() << endl;
- cout << node2.use_count() << endl;
-
- node1->_next = node2;
- node2->_prev = node1;
-
- cout << node1.use_count() << endl;
- cout << node2.use_count() << endl;
-
- return 0;
- }

如果不是new出来的对象如何通过智能指针管理呢?其实shared_ptr设计了一个删除器来解决这个问题。
- // 仿函数的删除器
- template<class T>
- struct FreeFunc {
- void operator()(T* ptr)
- {
- cout << "free:" << ptr << endl;
- free(ptr);
- }
- };
-
- template<class T>
- struct DeleteArrayFunc {
- void operator()(T* ptr)
- {
- cout << "delete[]" << ptr << endl;
- delete[] ptr;
- }
- };
-
- int main()
- {
- FreeFunc<int> freeFunc;
- std::shared_ptr<int> sp1((int*)malloc(4), freeFunc);
- DeleteArrayFunc<int> deleteArrayFunc;
- std::shared_ptr<int> sp2((int*)malloc(4), deleteArrayFunc);
-
- std::shared_ptr<int> sp4(new int[10], [](int* p) {delete[] p; });
- std::shared_ptr<FILE> sp5(fopen("test.txt", "w"), [](FILE* p)
- {fclose(p); });
-
- return 0;
- }

感谢各位大佬支持!!!
互三啦!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。