目录
1、问题引入
2、RAII和智能指针
3、C++标准库的智能指针
3.1 auto_ptr (不好)
3.2 unique_ptr
3.4 weak_ptr (重点)
6、C++11智能指针和boost的关系
7、内存泄漏
7.1 什么是内存泄漏,内存泄漏的危害
7.2 如何避免内存泄漏
1、问题引入
下面的程序中我们可以看到,new了以后,我们也delete了,
但是如果抛出异常导致后面的delete没有得到执行,所以就内存泄漏了。所以我们需要在new以后捕获异常,捕获到异常后delete,再把异常抛出,
但是new本身也可能会抛出异常,如果int* array2 = new int[10];时抛出异常,需要捕获异常,delete array1,再重新抛出,
由于try块通常捕获单一类型的异常,那么就需要多个try块,可能还要捕获,抛出,比较麻烦。
注意:都是资源泄漏的问题。
#include <iostream>
#include <exception>using namespace std;double Divide(int a, int b)
{// 当b == 0时抛出异常if (b == 0){throw "Divide by zero condition!";}return (double)a / (double)b;
}void Func()
{// 原始内存分配int* array1 = new int[10];int* array2 = new int[10]; // 这里可能抛出bad_alloc异常try{int len, time;cin >> len >> time;cout << Divide(len, time) << endl;}catch (...){// 异常处理中释放内存cout << "delete []" << array1 << endl;delete[] array1;cout << "delete []" << array2 << endl;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;
}
2、RAII和智能指针
RAII (资源获取立即初始化)是 Resource Acquisition Is Initialization 的缩写,它是一种管理资源的类的设计思想,这里的资源可以是内存、文件指针、网络连接、互斥锁等等。
RAII 的核心思想: 创建对象时就完成资源的获取操作,并且在对象的生命周期内持有该资源。当对象的生命周期结束,其所持有的资源会被自动释放(析构)。这样就把资源的管理和对象的生命周期紧密绑定起来。保障了资源的正常释放,避免资源泄漏问题。
智能指针类除了满足 RAII 的设计思想,
还会像迭代器类一样,重载 operator*/operator->/operator [] 等运算符,方便访问资源。
#include <iostream>
#include <exception>using namespace std;template<class T>
class SmartPtr
{
public:// RAII 构造函数SmartPtr(T* ptr):_ptr(ptr){}// 析构函数自动释放资源~SmartPtr(){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)
{// 当 b == 0 时抛出异常if (b == 0){throw "Divide by zero condition!";}return (double)a / (double)b;
}void Func()
{// 使用 RAII 的智能指针类管理数组SmartPtr<int> sp1 = new int[10];SmartPtr<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;}return 0;
}
3、C++标准库的智能指针
C++标准库中的智能指针都在头文件<memory>里面。
3.1 auto_ptr (不好)
auto_ptr 是C++98时设计出来的智能指针,
拷贝时把被拷贝对象的资源的管理权 转移给 拷贝对象(即始终只有一个对象管理资源),这是一个非常糟糕的设计,因为他会导致被拷贝对象悬空,访问报错的问题。C++11设计出新的智能指针后,强烈建议不要使用auto_ptr。其他C++11出来之前很多公司也是明令禁止使用这个智能指针的。
简单模拟实现:
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;// 转移资源所有权_ptr = 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; // 原始指针
};
3.2 unique_ptr
unique_ptr 是C++11设计出来的智能指针。翻译为唯一指针。
不支持拷贝,只支持移动。如果不需要拷贝的场景就非常建议使用他。
简单模拟实现:
template<class T>
class unique_ptr
{
public:// explicit 防止隐式转换explicit unique_ptr(T* ptr): _ptr(ptr){}// 析构函数(自动释放资源)~unique_ptr(){if (_ptr){cout << "delete:" << _ptr << endl;delete _ptr;}}// 禁用拷贝构造和拷贝赋值(=delete)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 (this != &sp) // 防止自移动{delete _ptr; // 释放当前资源_ptr = sp._ptr; // 接管新资源sp._ptr = nullptr;}return *this;}// 重载指针操作符T& operator*(){return *_ptr;}T* operator->(){return _ptr;}private:T* _ptr; // 管理的原始指针
};
3.3 shared_ptr (重点)
shared_ptr 是C++11设计出来的智能指针,支持拷贝,也支持移动。翻译为共享指针。
如果需要拷贝的场景就非常建议使用他了。底层是用引用计数的方式实现的。
简单模拟实现:
template <class T>
class shared_ptr
{
public:// explicit 防止隐式转换explicit shared_ptr(T* ptr):_ptr(ptr): _pcount(new int(1)){}~shared_ptr(){if (--(*_pcount) == 0){delete _ptr;delete _pcount;_ptr = _pcount = nullptr;}}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 = _pcount = nullptr;}_ptr = sp._ptr;_pcount = sp._pcount;++(*_pcount);}return *this;}T& operator*() const{return *_ptr;}T* operator->() const{return _ptr;}int use_pcount() const{return *_pcount;}T* get_ptr() const{return _ptr;}private:T* _ptr;int* _pcount;
};
注意:
1. 释放资源可能不匹配:
如果是new,就delete,如果是new [ ],就delete[ ],匹配使用,而且可能是FILE*类型的指针,不能delete, 应该是fclose。
解决方案:构造函数写成模板,传定制删除器。
定制删除器默认是delete,由于delete[ ]也比较常用,所以库里面特化了delete[ ]的版本(不用自己传delete[ ]定制删除器)。
shared_ptr一般传lambda表达式,更方便。如:
std::shared_ptr<Date[]> sp2(new Date[10]); // 特化
std::shared_ptr<Date> sp3(new Date[10], [](Date* ptr) {delete[] ptr; });
unique_ptr也传定制删除器,不过是在unique_ptr的模板参数传(传仿函数类型更方便)。如:
class Fclose
{
public:void operator()(FILE* ptr){cout << "fclose:" << ptr << endl;fclose(ptr);}
};std::unique_ptr<FILE, Fclose> up1(fopen("Test.cpp", "r"));
std::unique_ptr<Date[]> up2(new Date[10]); // 特化
所以:
#include <functional>namespace Lzc
{template <class T>class shared_ptr{public:// explicit 防止隐式转换explicit shared_ptr(T* ptr):_ptr(ptr): _pcount(new int(1)){}template<class D>explicit shared_ptr(T* ptr, D del):_ptr(ptr): _pcount(new int(1)): _del(del){}~shared_ptr(){if (--(*_pcount) == 0){_del(_ptr);delete _pcount;_ptr = _pcount = nullptr;}}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){_del(_ptr);delete _pcount;_ptr = _pcount = nullptr;}_ptr = sp._ptr;_pcount = sp._pcount;++(*_pcount);}return *this;}T& operator*() const{return *_ptr;}T* operator->() const{return _ptr;}int use_pcount() const{return *_pcount;}T* get_ptr() const{return _ptr;}private:T* _ptr;int* _pcount;function<void(T*)> _del = [](T* ptr) {delete ptr; };};
}
2.
template <class T, class... Args> shared_ptr<T> make_shared(Args&&... args);
std::shared_ptr<Date> sp1(new Date(2024, 9, 11));
std::shared_ptr<Date> sp2 = std::make_shared<Date>(2024, 9, 11);
区别就是,将资源和引用计数的空间一起开,减少空间碎片。
3. unique_ptr和shared_ptr都支持 operator bool 的类型转换,如果智能指针对象是一个空对象没有管理资源,则返回 false,否则返回 true,意味着可以直接用 if 判断是否为空。
4. unique_ptr和shared_ptr的构造函数都使用 explicit 修饰,防止普通指针隐式类型转换成智能指针对象。
3.4 weak_ptr (重点)
weak_ptr 是C++11设计出来的智能指针。翻译为弱指针。
不能单独管理资源(只能绑定share_ptr的资源),不增加对象的引用计数,主要用于解决 shared_ptr 循环引用造成的内存泄漏的问题。
weak_ptr也没有重载operator*和operator->等,不直接访问资源。
简单模拟实现:
// 需要注意的是我们这里实现的 shared_ptr 和 weak_ptr 都是以最简洁的方式实现的,
// 只能满足基本的功能,这里的 weak_ptr lock 等功能是无法实现的,想要实现就要
// 把 shared_ptr 和 weak_ptr 一起改了,把引用计数拿出来放到一个单独类型,
// shared_ptr 和 weak_ptr 都要存储指向这个类的对象才能实现,有兴趣可以去翻翻源代码template<class T>
class weak_ptr
{
public:weak_ptr() {}weak_ptr(const shared_ptr<T>& sp): _ptr(sp.get()){}weak_ptr<T>& operator=(const shared_ptr<T>& sp){_ptr = sp.get();return *this;}private:T* _ptr = nullptr;
};
注意:
如果weak_ptr绑定的 shared_ptr已经释放了资源,那么weak_ptr去访问资源就是很危险的。
weak_ptr支持expired检查指向的资源是否过期。过期返回true,否则返回false。
use_count也可获取shared_ptr的引用计数(这里如果shared_ptr的引用计数为0,就不能立即释放,还需要一个引用计数,判断是否还有weak_ptr指向)。expired即use_count() == 0。
weak_ptr可以调用 lock 返回一个管理资源的shared_ptr,如果资源已经被释放,返回的shared_ptr是一个空对象,如果资源没有释放,则通过返回的shared_ptr访问资源是安全的。
#include <iostream>
#include <memory>
#include <string>using namespace std;int main() {// 初始化共享指针和弱指针shared_ptr<string> sp1(new string("111111"));shared_ptr<string> sp2(sp1);weak_ptr<string> wp = sp1;// 检查弱指针状态cout << "Initial state:" << endl;cout << "wp.expired(): " << wp.expired() << endl; // 0 (未过期)cout << "wp.use_count(): " << wp.use_count() << endl; // 2 (sp1和sp2)// sp1指向新资源sp1 = make_shared<string>("222222");cout << "\nAfter sp1 reassignment:" << endl;cout << "wp.expired(): " << wp.expired() << endl; // 0 (sp2仍持有)cout << "wp.use_count(): " << wp.use_count() << endl; // 1 (仅sp2)// sp2指向新资源sp2 = make_shared<string>("333333");cout << "\nAfter sp2 reassignment:" << endl;cout << "wp.expired(): " << wp.expired() << endl; // 1 (已过期)cout << "wp.use_count(): " << wp.use_count() << endl; // 0// 重新绑定弱指针wp = sp1;auto sp3 = wp.lock(); // 提升为共享指针*sp3 += "###";cout << "\nAfter reusing wp:" << endl;cout << "wp.expired(): " << wp.expired() << endl; // 0cout << "wp.use_count(): " << wp.use_count() << endl; // 2 (sp1和sp3)// 输出最终内容cout << "\nFinal string: " << *sp1 << endl;return 0;
}
4、shared_ptr的循环引用问题(重点)
#include <iostream>
#include <memory>struct ListNode {int _data;/*ListNode* _next;ListNode* _prev;*//*std::shared_ptr<ListNode> _next;std::shared_ptr<ListNode> _prev;*/// 这里改成weak_ptr,当n1->_next = n2;绑定shared_ptr时// 不增加n2的引用计数,不参与资源释放的管理,就不会形成循环引用了std::weak_ptr<ListNode> _next;std::weak_ptr<ListNode> _prev;~ListNode() {std::cout << "~ListNode()" << std::endl;}
};int main() {// 循环引用 -- 内存泄露std::shared_ptr<ListNode> n1(new ListNode);std::shared_ptr<ListNode> n2(new ListNode);std::cout << n1.use_count() << std::endl;std::cout << n2.use_count() << std::endl;n1->_next = n2;n2->_prev = n1;std::cout << n1.use_count() << std::endl;std::cout << n2.use_count() << std::endl;return 0;
}
所以也可以用weak_ptr拷贝构造shared_ptr。
5、shared_ptr的线程安全问题
shared_ptr的引用计数对象在堆上,如果多个shared_ptr对象在多个线程中,进行shared_ptr的拷贝析构或析构时会修改引用计数,就会存在线程安全问题,所以shared_ptr引用计数是需要加锁或者原子操作保证线程安全的。
shared_ptr指向的对象也是有线程安全的问题的,但是这个对象的线程安全问题不归shared_ptr管,它也管不了,应该有外层使用shared_ptr的人进行线程安全的控制。
下面的程序会崩溃或者A资源没释放,
原子操作:shared_ptr引用计数从int*改成atomic<int>*就可以保证引用计数的线程安全,或者使用互斥锁加锁也可以。
#include <functional>
#include<atomic>namespace Lzc
{template <class T>class shared_ptr{public:// explicit 防止隐式转换explicit shared_ptr(T* ptr):_ptr(ptr): _pcount(new atomic<int>(1)){}template<class D>explicit shared_ptr(T* ptr, D del):_ptr(ptr): _pcount(new atomic<int>(1)): _del(del){}~shared_ptr(){if (--(*_pcount) == 0){_del(_ptr);delete _pcount;_ptr = _pcount = nullptr;}}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){_del(_ptr);delete _pcount;_ptr = _pcount = nullptr;}_ptr = sp._ptr;_pcount = sp._pcount;++(*_pcount);}return *this;}T& operator*() const{return *_ptr;}T* operator->() const{return _ptr;}int use_pcount() const{return *_pcount;}T* get_ptr() const{return _ptr;}private:T* _ptr;// int* _pcount;atomic<int>* _pcount; // 原子操作function<void(T*)> _del = [](T* ptr) {delete ptr; };};
}
struct AA {int _a1 = 0;int _a2 = 0;~AA() {cout << "~AA()" << endl;}
};int main() {Lzc::shared_ptr<AA> p(new AA); // 原始智能指针const size_t n = 100000; // 每个线程的循环次数mutex mtx; // 用于保护共享数据访问// 线程函数(lambda表达式)auto func = [&]() {for (size_t i = 0; i < n; ++i) {// 拷贝构造会递增引用计数Lzc::shared_ptr<AA> copy(p);{// 加锁保护AA对象成员的修改unique_lock<mutex> lk(mtx);copy->_a1++;copy->_a2++;}}};// 创建并启动两个线程thread t1(func);thread t2(func);// 等待线程结束t1.join();t2.join();// 输出最终结果cout << "Final _a1: " << p->_a1 << endl;cout << "Final _a2: " << p->_a2 << endl;cout << "Final use_count: " << p.use_count() << endl;return 0;
}
6、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中的实现的。
7、内存泄漏
7.1 什么是内存泄漏,内存泄漏的危害
什么是内存泄漏:内存泄漏指因为疏忽或错误造成程序未能释放已经不再使用的内存,一般是忘记释放或者发生异常释放程序未能执行导致的。内存泄漏并不是指内存在物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费。
内存泄漏的危害:普通程序运行一会就结束了出现内存泄漏问题也不大,进程正常结束,页表的映射关系解除,物理内存也可以释放。长期运行的程序出现内存泄漏,影响很大,如操作系统、后台服务、长时间运行的客户端等等,不断出现内存泄漏会导致可用内存不断变少,各种功能响应越来越慢,最终卡死。
7.2 如何避免内存泄漏
正确使用智能指针+定期检测。