C++(进阶) 第11智能指针

发布于:2025-04-10 ⋅ 阅读:(33) ⋅ 点赞:(0)

C++(进阶) 第11智能指针



前言

内存泄漏一直都是c++很难的一个问题,它不像java一样的有垃圾回收机制,c++给我们提供了更高的特权和速度,当在难度上也有所提高


一、智能指针的使用及其原理

1. 智能指针的使⽤场景分析

下⾯程序中我们可以看到,new了以后,我们也delete了,但是因为抛异常导,后⾯的delete没有得到执⾏,所以就内存泄漏了,所以我们需要new以后捕获异常,捕获到异常后delete内存,再把异常抛出,但是因为new本⾝也可能抛异常,连续的两个new和下⾯的Divide都可能会抛异常,让我们处理起来很⿇烦。智能指针放到这样的场景⾥⾯就让问题简单多了。

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;  
}  

二、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;  
    }  

    // Overloaded operators to mimic pointer behavior for easier resource access  
    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)  
{  
    // Throw exception when b == 0  
    if (b == 0)  
    {  
        throw "Divide by zero condition!";  
    }  
    else  
    {  
        return (double)a / (double)b;  
    }  
}  

void Func()  
{  
    // Using RAII smart pointer class to manage dynamically allocated arrays  
    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;  
}  

三、 C++标准库智能指针的使⽤

• C++标准库中的智能指针都在这个头⽂件下⾯,我们包含就可以是使⽤了,智能指针有好⼏种,除了weak_ptr他们都符合RAII和像指针⼀样访问的⾏为,原理上⽽⾔主要是解决智能指针拷⻉时的思路不同。

• auto_ptr是C++98时设计出来的智能指针,他的特点是拷⻉时把被拷⻉对象的资源的管理权转移给拷⻉对象,这是⼀个⾮常糟糕的设计,因为他会到被拷⻉对象悬空,访问报错的问题,C++11设计出新的智能指针后,强烈建议不要使⽤auto_ptr。其他C++11出来之前很多公司也是明令禁⽌使⽤这个智能指针的。

• unique_ptr是C++11设计出来的智能指针,他的名字翻译出来是唯⼀指针,他的特点的不⽀持拷⻉,只⽀持移动。如果不需要拷⻉的场景就⾮常建议使⽤他。

• shared_ptr是C++11设计出来的智能指针,他的名字翻译出来是共享指针,他的特点是⽀持拷⻉,也⽀持移动。如果需要拷⻉的场景就需要使⽤他了。底层是⽤引⽤计数的⽅式实现的。

• weak_ptr是C++11设计出来的智能指针,他的名字翻译出来是弱指针,他完全不同于上⾯的智能指针,他不⽀持RAII,也就意味着不能⽤它直接管理资源,weak_ptr的产⽣本质是要解决shared_ptr的⼀个循环引⽤导致内存泄漏的问题。具体细节下⾯我们再细讲。

• 智能指针析构时默认是进⾏delete释放资源,这也就意味着如果不是new出来的资源,交给智能指针管理,析构时就会崩溃。智能指针⽀持在构造时给⼀个删除器,所谓删除器本质就是⼀个可调⽤对象,这个可调⽤对象中实现你想要的释放资源的⽅式,当构造智能指针时,给了定制的删除器,在智能指针析构时就会调⽤删除器去释放资源。因为new[]经常使⽤,所以为了简洁⼀点,unique_ptr和shared_ptr都特化了⼀份[]的版本,使⽤时 unique_ptr<Date[]> up1(newDate[5]);shared_ptr<Date[]> sp1(new Date[5]); 就可以管理new []的资源。

• template <class T, class… Args> shared_ptr make_shared(Args&&… args);

• shared_ptr 除了⽀持⽤指向资源的指针构造,还⽀持 make_shared ⽤初始化资源对象的值直接构造。

• shared_ptr 和 unique_ptr 都⽀持了operator bool的类型转换,如果智能指针对象是⼀个空对象没有管理资源,则返回false,否则返回true,意味着我们可以直接把智能指针对象给if判断是否为空。

• shared_ptr 和 unique_ptr 都得构造函数都使⽤explicit 修饰,防⽌普通指针隐式类型转换成智能指针对象。

#include <iostream>  
#include <memory> // For smart pointers  

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()  
{  
    // Using auto_ptr (deprecated in C++11)  
    auto_ptr<Date> ap1(new Date);  
    
    // Copying an auto_ptr transfers ownership, leaving ap1 as a null pointer  
    auto_ptr<Date> ap2(ap1);  

    // Attempting to access ap1 now leads to undefined behavior  
    // ap1->_year++; // Uncommenting this will cause a runtime error  

    // Using unique_ptr  
    unique_ptr<Date> up1(new Date);  
    
    // Attempting to copy unique_ptr will result in a compile-time error  
    // unique_ptr<Date> up2(up1); // Uncommenting this will cause a compilation error  

    // Moving up1 transfers ownership, and up1 becomes null  
    unique_ptr<Date> up3(move(up1));  
    
    // Using shared_ptr  
    shared_ptr<Date> sp1(new Date);  
    
    // Copying a shared_ptr increases the reference count  
    shared_ptr<Date> sp2(sp1);  
    shared_ptr<Date> sp3(sp2);  
    
    cout << "Reference Count: " << sp1.use_count() << endl; // Should print 3  
    sp1->_year++;  
    cout << "sp1 Year: " << sp1->_year << endl; // Change reflected in all shared_ptrs  
    cout << "sp2 Year: " << sp2->_year << endl; // Should print the updated year  
    cout << "sp3 Year: " << sp3->_year << endl; // Should also print the updated year  

    // Moving a shared_ptr will leave the moved-from pointer null  
    shared_ptr<Date> sp4(move(sp1));  

    return 0;  
}  
#include <iostream>  
#include <memory> // For smart pointers  
#include <cstdio> // For FILE and fclose  

using namespace std;  

// Function that deletes an array of type T  
template<class T>  
void DeleteArrayFunc(T* ptr)  
{  
    delete[] ptr;  
}  

// Functor class for deleting arrays  
template<class T>  
class DeleteArray  
{  
public:  
    void operator()(T* ptr)  
    {  
        delete[] ptr;  
    }  
};  

// Functor class for closing FILE pointers  
class Fclose  
{  
public:  
    void operator()(FILE* ptr)  
    {  
        cout << "fclose: " << ptr << endl;  
        fclose(ptr);  
    }  
};  

int main()  
{  
    // Avoiding crashes by using the correct deletion method  
    // unique_ptr<Date[]> up1(new Date[10]); // Crashes without custom deleter  
    // shared_ptr<Date[]> sp1(new Date[10]); // Crashes without custom deleter  
    
    // Solution 1: Using the specialization for arrays  
    unique_ptr<Date[]> up1(new Date[5]);  
    shared_ptr<Date[]> sp1(new Date[5]);  

    // Solution 2: Functor as a deleter  
    // unique_ptr<Date, DeleteArray<Date>> up2(new Date[5], DeleteArray<Date>());  
    // unique_ptr and shared_ptr handle deleters differently  
    // unique_ptr expects the deleter as a template parameter  
    // shared_ptr takes the deleter as a constructor parameter  
    
    unique_ptr<Date, DeleteArray<Date>> up2(new Date[5]);  
    shared_ptr<Date> sp2(new Date[5], DeleteArray<Date>());  

    // Using a function pointer as a deleter  
    unique_ptr<Date, void(*)(Date*)> up3(new Date[5], DeleteArrayFunc<Date>);  
    shared_ptr<Date> sp3(new Date[5], DeleteArrayFunc<Date>());  

    // Using a lambda expression as a deleter  
    auto delArrOBJ = [](Date* ptr) { delete[] ptr; };  
    unique_ptr<Date, decltype(delArrOBJ)> up4(new Date[5], delArrOBJ);  
    shared_ptr<Date> sp4(new Date[5], delArrOBJ);  

    // Managing other resource types with custom deleters  
    shared_ptr<FILE> sp5(fopen("Test.cpp", "r"), Fclose());  
    shared_ptr<FILE> sp6(fopen("Test.cpp", "r"), [](FILE* ptr) {  
        cout << "fclose: " << ptr << endl;  
        fclose(ptr);  
    });  

    return 0;  
}  
#include <iostream>  
#include <memory>  
using namespace std;  

class Date {  
public:  
    Date(int year, int month, int day) {  
        // Constructor implementation  
    }  
};  

int main() {  
    shared_ptr<Date> sp1(new Date(2024, 9, 11));  
    shared_ptr<Date> sp2 = make_shared<Date>(2024, 9, 11);  
    auto sp3 = make_shared<Date>(2024, 9, 11);  
    shared_ptr<Date> sp4;  

    // Check if sp1 is not nullptr  
    if (sp1) {  
        cout << "sp1 is not nullptr" << endl;  
    }  
    
    // Check if sp4 is nullptr  
    if (!sp4) {  
        cout << "sp4 is nullptr" << endl; // Corrected from "sp1 is nullptr"  
    }  

    // The following lines will cause compilation errors  
    // shared_ptr<Date> sp5 = new Date(2024, 9, 11); // Error: cannot assign a raw pointer to shared_ptr  
    // unique_ptr<Date> sp6 = new Date(2024, 9, 11); // Error: cannot assign a raw pointer to unique_ptr  
    
    return 0;  
}  

四、 智能指针的原理

• 下⾯我们模拟实现了auto_ptrunique_ptr的核⼼功能,这两个智能指针的实现⽐较简单,⼤家了解⼀下原理即可。auto_ptr的思路是拷⻉时转移资源管理权给被拷⻉对象,这种思路是不被认可的,也不建议使⽤。unique_ptr的思路是不⽀持拷⻉。⼤家重点要看看shared_ptr是如何设计的,尤其是引⽤计数的设计,主要这⾥⼀份资源就需要⼀个引⽤计数,所以引⽤计数才⽤静态成员的⽅式是⽆法实现的,要使⽤堆上动态开辟的⽅式,构造智能指针对象时来⼀份资源,就要new⼀个引⽤计数出来。多个shared_ptr指向资源时就++引⽤计数,shared_ptr对象析构时就–引⽤计数,引⽤计数减到0时代表当前析构的shared_ptr是最后⼀个管理资源的对象,则析构资源。

在这里插入图片描述

#include <iostream>  
#include <functional>  

namespace bit {  

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 = nullptr;  
        }  
        return *this;  
    }  

    ~auto_ptr() {  
        if (_ptr) {  
            std::cout << "delete: " << _ptr << std::endl;  
            delete _ptr;  
        }  
    }  

    // 像指针⼀样使⽤  
    T& operator*() {  
        return *_ptr;  
    }  

    T* operator->() {  
        return _ptr;  
    }  

private:  
    T* _ptr;  
};  

template<class T>  
class unique_ptr {  
public:  
    explicit unique_ptr(T* ptr)  
        : _ptr(ptr) {}  

    ~unique_ptr() {  
        if (_ptr) {  
            std::cout << "delete: " << _ptr << std::endl;  
            delete _ptr;  
        }  
    }  

    // 像指针⼀样使⽤  
    T& operator*() {  
        return *_ptr;  
    }  

    T* operator->() {  
        return _ptr;  
    }  

    unique_ptr(const unique_ptr<T>& sp) = delete; // No copy  
    unique_ptr<T>& operator=(const unique_ptr<T>& sp) = delete; // No copy assignment  

    unique_ptr(unique_ptr<T>&& sp)  
        : _ptr(sp._ptr) {  
        sp._ptr = nullptr;  
    }  

    unique_ptr<T>& operator=(unique_ptr<T>&& sp) {  
        delete _ptr;  
        _ptr = sp._ptr;  
        sp._ptr = nullptr;  
        return *this;  
    }  

private:  
    T* _ptr;  
};  

template<class T>  
class shared_ptr {  
public:  
    explicit shared_ptr(T* ptr = nullptr)  
        : _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(const shared_ptr<T>& sp)  
        : _ptr(sp._ptr), _pcount(sp._pcount), _del(sp._del) {  
        ++(*_pcount);  
    }  

    void release() {  
        if (--(*_pcount) == 0) {  
            // 最后⼀个管理的对象,释放资源  
            _del(_ptr);  
            delete _pcount;  
            _ptr = nullptr;  
            _pcount = nullptr;  
        }  
    }  

    shared_ptr<T>& operator=(const shared_ptr<T>& sp) {  
        if (_ptr != sp._ptr) {  
            release();  
            _ptr = sp._ptr;  
            _pcount = sp._pcount;  
            ++(*_pcount);  
            _del = sp._del;  
        }  
        return *this;  
    }  

    ~shared_ptr() {  
        release();  
    }  

    T* get() const {  
        return _ptr;  
    }  

    int use_count() const {  
        return *_pcount;  
    }  

    T& operator*() {  
        return *_ptr;  
    }  

    T* operator->() {  
        return _ptr;  
    }  

private:  
    T* _ptr;  
    int* _pcount;  
    std::function<void(T*)> _del = [](T* ptr) { delete ptr; };  
};  

// 需要注意的是我们这⾥实现的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;  
};  

} // namespace bit  

int main() {  
    bit::auto_ptr<Date> ap1(new Date);  
    // 拷⻉时,管理权限转移,被拷⻉对象ap1悬空  
    bit::auto_ptr<Date> ap2(ap1);  
    // 空指针访问,ap1对象已经悬空  
    // ap1->_year++;  

    bit::unique_ptr<Date> up1(new Date);  
    // 不⽀持拷⻉  
    // unique_ptr<Date> up2(up1);  
    // ⽀持移动,但是移动后up1也悬空,所以使⽤移动要谨慎  
    bit::unique_ptr<Date> up3(std::move(up1));  

    bit::shared_ptr<Date> sp1(new Date);  
    // ⽀持拷⻉  
    bit::shared_ptr<Date> sp2(sp1);  
    bit::shared_ptr<Date> sp3(sp2);  
    std::cout << sp1.use_count() << std::endl;  
    
    sp1->_year++;  
    std::cout << sp1->_year << std::endl;  
    std::cout << sp2->_year << std::endl;  
    std::cout << sp3->_year << std::endl;  

    return 0;  
}  

五、 shared_ptr和weak_ptr

5.1 shared_ptr循环引⽤问题

• shared_ptr⼤多数情况下管理资源⾮常合适,⽀持RAII,也⽀持拷⻉。但是在循环引⽤的场景下会导致资源没得到释放内存泄漏,所以我们要认识循环引⽤的场景和资源没释放的原因,并且学会使⽤weak_ptr解决这种问题。

• 如下图所述场景,n1和n2析构后,管理两个节点的引⽤计数减到1

  1. 右边的节点什么时候释放呢,左边节点中的_next管着呢,_next析构后,右边的节点就释放了。
  2. _next什么时候析构呢,_next是左边节点的的成员,左边节点释放,_next就析构了。
  3. 左边节点什么时候释放呢,左边节点由右边节点中的_prev管着呢,_prev析构后,左边的节点就释
    放了。
  4. _prev什么时候析构呢,_prev是右边节点的成员,右边节点释放,_prev就析构了。
    • ⾄此逻辑上成功形成回旋镖似的循环引⽤,谁都不会释放就形成了循环引⽤,导致内存泄漏
    • 把ListNode结构体中的_next和_prev改成weak_ptr,weak_ptr绑定到shared_ptr时不会增加它的
    引⽤计数,_next和_prev不参与资源释放管理逻辑,就成功打破了循环引⽤,解决了这⾥的问题

在这里插入图片描述
在这里插入图片描述

#include <iostream>  
#include <memory>  

struct ListNode {  
    int _data;                                                    // Data of the node  
    std::shared_ptr<ListNode> _next;                           // Pointer to the next node  
    std::shared_ptr<ListNode> _prev;                           // Pointer to the previous node  

    // Uncomment the following lines to use weak_ptr to avoid circular references  
    /*  
    std::weak_ptr<ListNode> _next;  
    std::weak_ptr<ListNode> _prev;  
    */  

    ~ListNode() {  
        std::cout << "~ListNode()" << std::endl;                // Destructor output  
    }  
};  

int main() {  
    // Demonstrating circular reference causing memory leak  
    std::shared_ptr<ListNode> n1(new ListNode);  
    std::shared_ptr<ListNode> n2(new ListNode);  
    
    std::cout << n1.use_count() << std::endl;                  // Use count for n1  
    std::cout << n2.use_count() << std::endl;                  // Use count for n2  
    
    n1->_next = n2;                                            // Linking n1 to n2  
    n2->_prev = n1;                                            // Linking n2 back to n1  
    
    std::cout << n1.use_count() << std::endl;                  // Updated use count for n1  
    std::cout << n2.use_count() << std::endl;                  // Updated use count for n2  

    // weak_ptr doesn't manage resources and doesn't support RAII  
    // Example of weak_ptr binding to shared_ptr without increasing reference count  
    // std::weak_ptr<ListNode> wp(new ListNode);  

    return 0;  
}  

5.2 weak_ptr

• weak_ptr不⽀持RAII,也不⽀持访问资源,所以我们看⽂档发现weak_ptr构造时不⽀持绑定到资源,只⽀持绑定到shared_ptr,绑定到shared_ptr时,不增加shared_ptr的引⽤计数,那么就可以解决上述的循环引⽤问题。

• weak_ptr也没有重载operator*operator->等,因为他不参与资源管理,那么如果他绑定的shared_ptr已经释放了资源,那么他去访问资源就是很危险的。weak_ptr⽀持expired检查指向的资源是否过期use_count也可获取shared_ptr的引⽤计数,weak_ptr想访问资源时,可以调⽤
lock返回⼀个管理资源的shared_ptr,如果资源已经被释放,返回的shared_ptr是⼀个空对象,如果资源没有释放,则通过返回的shared_ptr访问资源是安全的。

#include <iostream>  
#include <memory>  
#include <string>  

int main() {  
    // Create a shared pointer to a string  
    std::shared_ptr<std::string> sp1(new std::string("111111"));  
    std::shared_ptr<std::string> sp2(sp1);                 // Copy sp1 into sp2  
    std::weak_ptr<std::string> wp = sp1;                   // Create a weak pointer from sp1  

    // Check if the weak pointer is expired and print use count  
    std::cout << wp.expired() << std::endl;                // Outputs 0 (false)  
    std::cout << wp.use_count() << std::endl;              // Outputs 2 (sp1 and sp2)  

    // Assign a new string to sp1, causing wp to expire  
    sp1 = std::make_shared<std::string>("222222");  
    std::cout << wp.expired() << std::endl;                // Outputs 1 (true)  
    std::cout << wp.use_count() << std::endl;              // Outputs 0 (no shared_ptr pointing to the string)  

    // Assign a new string to sp2, which is independent of wp  
    sp2 = std::make_shared<std::string>("333333");  
    std::cout << wp.expired() << std::endl;                // Outputs 1 (true)  
    std::cout << wp.use_count() << std::endl;              // Outputs 0  

    // Reassign wp to the new shared_ptr sp1  
    wp = sp1;  

    // Lock the weak pointer to get a shared_ptr  
    auto sp3 = wp.lock();  
    
    // Check the state of the weak pointer again  
    std::cout << wp.expired() << std::endl;                // Outputs 0 (false)  
    std::cout << wp.use_count() << std::endl;              // Outputs 1 (sp1)  

    // Modify the string pointed to by sp3  
    *sp3 += "###";  
    std::cout << *sp1 << std::endl;                         // Outputs: 222222###  

    return 0;  
}  

六、 shared_ptr的线程安全问题

• shared_ptr的引⽤计数对象在堆上,如果多个shared_ptr对象在多个线程中,进⾏shared_ptr的拷⻉析构时会访问修改引⽤计数,就会存在线程安全问题,所以shared_ptr引⽤计数是需要加锁或者原⼦操作保证线程安全的。

• shared_ptr指向的对象也是有线程安全的问题的,但是这个对象的线程安全问题不归shared_ptr管,它也管不了,应该有外层使⽤shared_ptr的⼈进⾏线程安全的控制

• 下⾯的程序会崩溃或者A资源没释放,bit::shared_ptr引⽤计数从int*改成atomic*就可以保证引⽤计数的线程安全问题,或者使⽤互斥锁加锁也可以。

#include <iostream>  
#include <thread>  
#include <mutex>  
#include <memory> // Ensure this is included if you use smart pointers  

namespace bit {  
    template<typename T>  
    using shared_ptr = std::shared_ptr<T>; // Assuming you're aliasing shared_ptr to std::shared_ptr  
}  

struct AA {  
    int _a1 = 0;  // Initialize _a1 to 0  
    int _a2 = 0;  // Initialize _a2 to 0  
    
    ~AA() {  
        std::cout << "~AA()" << std::endl; // Destructor output  
    }  
};  

int main() {  
    bit::shared_ptr<AA> p(new AA); // Create a shared pointer to AA  
    const size_t n = 100000;         // Define a constant for the loop count  
    std::mutex mtx;                  // Mutex for thread synchronization  

    // Lambda function to increment _a1 and _a2  
    auto func = [&]() {  
        for (size_t i = 0; i < n; ++i) {  
            // Here the smart pointer copy will increment the reference count  
            bit::shared_ptr<AA> copy(p);  
            {  
                std::unique_lock<std::mutex> lk(mtx); // Lock the mutex  
                copy->_a1++; // Increment _a1  
                copy->_a2++; // Increment _a2  
            }  
        }  
    };  

    // Create two threads to run the function concurrently  
    std::thread t1(func);  
    std::thread t2(func);  

    // Wait for both threads to finish  
    t1.join();  
    t2.join();  

    // Output the final values and use count  
    std::cout << p->_a1 << std::endl; // Display the final value of _a1  
    std::cout << p->_a2 << std::endl; // Display the final value of _a2  
    std::cout << p.use_count() << std::endl; // Display the use count of the shared_ptr  

    return 0;  
}  

七. 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下内存泄漏检测: https://blog.csdn.net/gatieme/article/details/51959654

• windows下的内存泄露检测工具VLD使用
https://blog.csdn.net/lonely1047/article/details/120038929

8.3 如何避免内存泄漏

• ⼯程前期良好的设计规范,养成良好的编码规范,申请的内存空间记着匹配的去释放。ps:这个理想状态。但是如果碰上异常时,就算注意释放了,还是可能会出问题。需要下⼀条智能指针来管理才有保证。

• 尽量使⽤智能指针来管理资源,如果⾃⼰场景⽐较特殊,采⽤RAII思想⾃⼰造个轮⼦管理。

• 定期使⽤内存泄漏⼯具检测,尤其是每次项⽬快上线前,不过有些⼯具不够靠谱,或者是收费。

• 总结⼀下:内存泄漏⾮常常⻅,解决⽅案分为两种:1、事前预防型。如智能指针等。2、事后查错型。如泄漏检测⼯具。