C++ 11 -智能指针

目录

1.引入:为什么需要智能指针

2. 内存泄漏

2.1 什么是内存泄漏,内存泄漏的危害

2.2 内存泄漏分类(了解)

2.3 如何检测内存泄漏(了解)

2.4如何避免内存泄漏

3.智能指针的使用及原理

3.1 RAII

3.2 智能指针的原理

3.3 std::auto_ptr

3.4 std::unique_ptr

3.5 std::shared_ptr

4.C++11和boost中智能指针的关系

本节主要介绍智能指针的相关用法。

1.引入:为什么需要智能指针
    

下面我们先分析一下下面这段程序有没有什么 内存方面 的问题?提示一下:注意分析 MergeSort函数中的问题。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
int div()
{
 
    int a, b;
    cin >> a >> b;
    if (b == 0)
        throw invalid_argument("zero was div");
    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 (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }
 
    system("pause");
    return 0;
}

2. 内存泄漏
2.1 什么是内存泄漏,内存泄漏的危害
什么是内存泄漏:内存泄漏指因为疏忽或错误造成程序未能释放已经不再使用的内存的情况。内存泄漏并不是指内存在物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费。内存泄漏的危害:长期运行的程序出现内存泄漏,影响很大,如操作系统、后台服务等等,出现 内存泄漏会导致响应越来越慢,最终卡死。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
int div()
{
 
    int a, b;
    cin >> a >> b;
    if (b == 0)
        throw invalid_argument("zero was div");
    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;
}
 
 
void MemoryLeaks(){
 
    int *p1=(int*)malloc(sizeof(int));
    int *p2=new int;
 
    int *p3=new int[10];
 
    //这里Func() 函数抛异常,导致delete []p3 没有执行
    Func();
 
    delete []p3;
 
 
}
 
 
int main()
{
 
    // try
    // {
    //     Func();
    // }
    // catch (const std::exception &e)
    // {
    //     std::cerr << e.what() << '\n';
    // }
 
    try
    {
        MemoryLeaks();
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
    }
    
 
    system("pause");
    return 0;
}

2.2 内存泄漏分类(了解)
C/C++ 程序中一般我们关心两种方面的内存泄漏:
堆内存泄漏(Heap leak)
 堆内存指的是程序执行中依据须要分配通过 malloc / calloc / realloc / new 等从堆中分配的一块内存,用完后必须通过调用相应的 free 或者 delete 删掉。假设程序的设计错误导致这部分内存没有被释放,那么以后这部分空间将无法再被使用,就会产生Heap Leak 。
系统资源泄漏
  指程序使用系统分配的资源,比方套接字、文件描述符、管道等没有使用对应的函数释放掉,导致系统资源的浪费,严重可导致系统效能减少,系统执行不稳定。
2.3 如何检测内存泄漏(了解)
在 linux 下内存泄漏检测: linux 下几款内存泄漏检测工具
在 windows 下使用第三方工具: VLD 工具说明
其他工具: 内存泄漏工具比较
2.4如何避免内存泄漏
1. 工程前期良好的设计规范,养成良好的编码规范,申请的内存空间记着匹配的去释放。 ps :这个理想状态。但是如果碰上异常时,就算注意释放了,还是可能会出问题。需要下一条智能指针来管理才有保证。
2. 采用 RAII 思想或者智能指针来管理资源。
3. 有些公司内部规范使用内部实现的私有内存管理库。这套库自带内存泄漏检测的功能选项。
4. 出问题了使用内存泄漏工具检测。 ps :不过很多工具都不够靠谱,或者收费昂贵。
总结一下 :
内存泄漏非常常见,解决方案分为两种: 1 、事前预防型。如智能指针等。 2 、事后查错型。如泄
漏检测工具
3.智能指针的使用及原理
3.1 RAII
RAII ( Resource Acquisition Is Initialization )是一种 利用对象生命周期来控制程序资源 (如内
存、文件句柄、网络连接、互斥量等等)的简单技术。
在对象构造时获取资源 ,接着控制对资源的访问使之在对象的生命周期内始终保持有效, 最后在
对象析构的时候释放资源 。借此,我们实际上把管理一份资源的责任托管给了一个对象。这种做
法有两大好处:
不需要显式地释放资源。
采用这种方式,对象所需的资源在其生命期内始终保持有效。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
 
template<class T>
// 使用RAII思想设计的SmartPtr类
 
class smartPtr{
 
    public:
        smartPtr(T *ptr):_ptr(ptr){
            cout<<"construct"<<endl;
        }
 
 
        ~smartPtr(){
            if(_ptr)
                {
                    delete _ptr;
                }
            cout<<"Destruction"<<endl;
        }
 
 
private:
    T *_ptr;
 
 
};
 
 
int div(){
    int a,b;
    cin>>a>>b;
 
    if(b==0)
        throw invalid_argument("zero was div");
    
    return 0;
}
 
void Func(){
 
 
    smartPtr<int> sp1(new int);
    smartPtr<int> sp2(new int);
 
    cout<<div()<<endl;
 
}
 
 
 
 
int main()
{
 
try
{
    Func();
}
catch(const std::exception& e)
{
    std::cerr << e.what() << '\n';
}
 
 
 
 
 
system("pause");
return 0;
}

以下是结果,由此可见,即使抛了异常,类被销毁了也,内存也会释放。


3.2 智能指针的原理
上述的 SmartPtr 还不能将其称为智能指针,因为它还不具有指针的行为。指针可以解引用,也可
以通过 -> 去访问所指空间中的内容,因此: AutoPtr 模板类中还得需要将 * 、 -> 重载下,才可让其
像指针一样去使用 。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
template <class T>
// 使用RAII思想设计的SmartPtr类
 
class smartPtr
{
 
public:
    smartPtr(T *ptr) : _ptr(ptr)
    {
        cout << "construct" << endl;
    }
    //解引用的重载
    T &operator*()
    {
        return *_ptr;
    }
 
    T *operator->()
    {
        return _ptr;
    }
 
    ~smartPtr()
    {
        if (_ptr)
        {
            delete _ptr;
        }
        cout << "Destruction" << endl;
    }
 
private:
    T *_ptr;
};
 
int div()
{
    int a, b;
    cin >> a >> b;
 
    if (b == 0)
        throw invalid_argument("zero was div");
 
    return 0;
}
 
void Func()
{
 
    smartPtr<int> sp1(new int);
    smartPtr<int> sp2(new int);
 
    cout << div() << endl;
}
 
class Date{
    public:
    int _year;
    int _month;
    int _day;
 
};
 
void test01(){
    smartPtr<int> sp1(new int);
    *sp1=10;
    cout<<*sp1<<endl;
 
    smartPtr<Date> sp(new Date);
    sp->_year=2018;
    sp->_month=1;
    sp->_day=1;
 
    cout<<sp->_month<<sp->_year<<sp->_day<<endl;
    
    
    }
 
 
 
 
 
 
 
int main()
{
 
    test01();
    // try
    // {
    //     Func();
    // }
    // catch (const std::exception &e)
    // {
    //     std::cerr << e.what() << '\n';
    // }
 
    system("pause");
    return 0;
}

总结一下智能指针的原理:
1. RAII 特性
2. 重载 operator* 和 opertaor-> ,具有像指针一样的行为。
3.3 std::auto_ptr
C++98 版本的库中就提供了 auto_ptr 的智能指针。下面演示的 auto_ptr 的使用及问题。 auto_ptr 的实现原理:管理权转移的思想,下面简化模拟实现了一份 bit::auto_ptr 来了解它的原 理
#include<iostream>
#include<vector>
 
#include<algorithm>
using namespace std;
 
 
namespace myspace
{
    
    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=NULL;
                }
 
                return *this;
            }
 
            ~auto_ptr(){
                if(_ptr){
                    cout<<"delete:"<<_ptr<<endl;
                    delete _ptr;
                }
            }
 
            T &operator*(){
                return *_ptr;
            }
 
            T *operator->(){
                return _ptr;
            }
 
 
        private:
            T *_ptr;
 
    };
 
 
} // namespace myspace
 
 
 
 
// 结论:auto_ptr是一个失败设计,很多公司明确要求不能使用auto_ptr
 
int main()
{
 
 myspace::auto_ptr<int> sp1(new int);
 myspace::auto_ptr<int> sp2(sp1);
 
 *sp2=10;
 cout<<*sp2<<endl;
 cout<<*sp1<<endl;
 
 
 
system("pause");
return 0;
}

3.4 std::unique_ptr
        

C++11 中开始提供更靠谱的 unique_ptr
unique_ptr 的实现原理:简单粗暴的防拷贝,下面简化模拟实现了一份 UniquePtr 来了解它的原
理。
        
// 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
// 原理:简单粗暴 -- 防拷贝
 
#include <iostream>
#include <vector>
#include <memory>
#include <algorithm>
using namespace std;
 
namespace myspace
{
    template <class T>
    class unique_ptr
    {
        public:
        unique_ptr(T *ptr) : _ptr(ptr)
        {
        }
 
        ~unique_ptr()
        {
 
            if (_ptr)
            {
                cout << "delete _ptr" << _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;
    };
 
} // namespace myspace
 
void test01()
{
 
    // myspace::unique_ptr<int> sp(new int);
    // myspace::unique_ptr<int> sp2(sp); 报错
 
    unique_ptr<int> sp(new int);
    // unique_ptr<int> sp2(sp);
}
 
int main()
{
 
    test01();
 
    system("pause");
    return 0;
}

3.5 std::shared_ptr
C++11 中开始提供更靠谱的并且支持拷贝的 shared_ptr
shared_ptr 的原理:是通过引用计数的方式来实现多个 shared_ptr 对象之间共享资源 。例如: 刘老师晚上在下班之前都会通知,让最后走的学生记得把门锁下。
1. shared_ptr 在其内部, 给每个资源都维护了着一份计数,用来记录该份资源被几个对象共 享 。
2. 在 对象被销毁时 ( 也就是析构函数调用 ) ,就说明自己不使用该资源了,对象的引用计数减一。
3. 如果引用计数是 0 ,就说明自己是最后一个使用该资源的对象, 必须释放该资源 ;
4. 如果不是 0 ,就说明除了自己还有其他对象在使用该份资源, 不能释放该资源 ,否则其他对象就成野指针了。
// 引用计数支持多个拷贝管理同一个资源,最后一个析构对象释放资源
#include <iostream>
#include <vector>
#include <mutex>
#include <algorithm>
using namespace std;
 
namespace myspace
{
 
    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 Addref()
        {
            _pmtx->lock();
            ++(*_pRefCount);
            _pmtx->unlock();
        }
 
        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;
            }
        }
 
        shared_ptr<T> &operator=(const shared_ptr<T> &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;
    };
 
    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;
    };
 
}
 
int main()
{
 
    myspace::shared_ptr<int> sp1(new int);
    myspace::shared_ptr<int> sp2(sp1);
    myspace::shared_ptr<int> sp3(sp1);
 
 
    myspace::shared_ptr<int> sp4(new int);
    myspace::shared_ptr<int> sp5(sp4);
 
    sp1=sp2;
 
    *sp2=3;
 
 
 
 
 
 
 
    system("pause");
    return 0;
}
问题:
// shared_ptr 智能指针是线程安全的吗?
// 是的,引用计数的加减是加锁保护的。但是指向资源不是线程安全的
// 指向堆上资源的线程安全问题是访问的人处理的,智能指针不管,也管不了
// 引用计数的线程安全问题,是智能指针要处理的
std::shared_ptr的线程安全问题
通过下面的程序我们来测试 shared_ptr 的线程安全问题。需要注意的是 shared_ptr 的线程安全分
为两方面:
1. 智能指针对象中引用计数是多个智能指针对象共享的,两个线程中智能指针的引用计数同时
++ 或 -- ,这个操作不是原子的,引用计数原来是 1 , ++ 了两次,可能还是 2. 这样引用计数就错
乱了。会导致资源未释放或者程序崩溃的问题。所以只能指针中引用计数 ++ 、 -- 是需要加锁
的,也就是说引用计数的操作是线程安全的。
2. 智能指针管理的对象存放在堆上,两个线程中同时去访问,会导致线程安全问题。
// 1. 演示引用计数线程安全问题,就把 AddRefCount 和 SubRefCount 中的锁去掉
// 2. 演示可能不出现线程安全问题,因为线程安全问题是偶现性问题, main 函数的 n 改大一些概率就
变大了,就容易出现了。
// 3. 下面代码我们使用 SharedPtr 演示,是为了方便演示引用计数的线程安全问题,将代码中的
SharedPtr 换成 shared_ptr 进行测试,可以验证库的 shared_ptr ,发现结论是一样的。
#include <iostream>
#include <vector>
#include <mutex>
#include<thread>
#include <algorithm>
using namespace std;
 
namespace myspace
{
 
    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 Addref()
        {
            // _pmtx->lock();
            ++(*_pRefCount);
            // _pmtx->unlock();
        }
 
        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;
            }
        }
 
        shared_ptr<T> &operator=(const shared_ptr<T> &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;
    };
 
    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(myspace::shared_ptr<Date> &sp, size_t n, mutex &mtx)
{
 
    cout << sp.get() << endl;
 
    for (size_t i = 0; i < n; ++i)
    {
 
        // 这里智能指针拷贝会++计数,智能指针析构会--计数,这里是线程安全的。
        myspace::shared_ptr<Date> copy(sp);
 
        // 这里智能指针访问管理的资源,不是线程安全的。所以我们看看这些值两个线程++了2n
        // 次,但是最终看到的结果,并一定是加了2n
        {
            unique_lock<mutex> lk(mtx);
 
            copy->_year++;
            copy->_month++;
            copy->_day++;
 
 
        }
    }
}
 
void test02(){
 
    myspace::shared_ptr<Date> p(new Date);
 
    cout<<p.get()<<endl;
 
    const size_t n=100000;
    mutex mtx;
 
    thread t1(SharePtrFunc,ref(p),n,ref(mtx));
    thread t2(SharePtrFunc,ref(p),n,ref(mtx));
 
 
    t1.join();
    t2.join();
 
    cout<<p->_year<<endl;
    cout<<p->_month<<endl;
    cout<<p->_day<<endl;
 
    cout<<p.use_count()<<endl;
 
 
}
 
int main()
{
 
    test02();
    cout<<"hello"<<endl;
 
    // myspace::shared_ptr<int> sp1(new int);
    // myspace::shared_ptr<int> sp2(sp1);
    // myspace::shared_ptr<int> sp3(sp1);
    // myspace::shared_ptr<int> sp4(new int);
    // myspace::shared_ptr<int> sp5(sp4);
    // sp1 = sp2;
    // *sp2 = 3;
 
    system("pause");
    return 0;
}
std::shared_ptr 的循环引用
循环引用分析:
1. node1 和 node2 两个智能指针对象指向两个节点,引用计数变成 1 ,我们不需要手动delete。
2. node1 的 _next 指向 node2 , node2 的 _prev 指向 node1 ,引用计数变成 2 。
3. node1 和 node2 析构,引用计数减到 1 ,但是 _next 还指向下一个节点。但是 _prev 还指向上一个节点。
4. 也就是说 _next 析构了, node2 就释放了。
5. 也就是说 _prev 析构了, node1 就释放了。
6. 但是 _next 属于 node 的成员, node1 释放了, _next 才会析构,而 node1 由 _prev 管理, _prev
属于 node2 成员,所以这就叫循环引用,谁也不会释放。
#include <iostream>
#include <vector>
#include <mutex>
#include<thread>
#include <algorithm>
using namespace std;
 
namespace myspace
{
 
    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 Addref()
        {
            _pmtx->lock();
            ++(*_pRefCount);
            _pmtx->unlock();
        }
 
        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;
            }
        }
 
        shared_ptr<T> &operator=(const shared_ptr<T> &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;
    };
 
    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(myspace::shared_ptr<Date> &sp, size_t n, mutex &mtx)
{
 
    cout << sp.get() << endl;
 
    for (size_t i = 0; i < n; ++i)
    {
 
        // 这里智能指针拷贝会++计数,智能指针析构会--计数,这里是线程安全的。
        myspace::shared_ptr<Date> copy(sp);
 
        // 这里智能指针访问管理的资源,不是线程安全的。所以我们看看这些值两个线程++了2n
        // 次,但是最终看到的结果,并一定是加了2n
        {
            unique_lock<mutex> lk(mtx);
 
            copy->_year++;
            copy->_month++;
            copy->_day++;
 
 
        }
    }
}
 
void test02(){
 
    myspace::shared_ptr<Date> p(new Date);
 
    cout<<p.get()<<endl;
 
    const size_t n=100000;
    mutex mtx;
 
    thread t1(SharePtrFunc,ref(p),n,ref(mtx));
    thread t2(SharePtrFunc,ref(p),n,ref(mtx));
 
 
    t1.join();
    t2.join();
 
    cout<<p->_year<<endl;
    cout<<p->_month<<endl;
    cout<<p->_day<<endl;
 
    cout<<p.use_count()<<endl;
 
 
}
 
 
struct ListNode
{
    int _data;
    shared_ptr<ListNode> _next;
    shared_ptr<ListNode> _prev;
    ~ListNode(){
        cout<<"~ListNode()"<<endl;
 
    }
};
 
void test03(){
 
   std:: shared_ptr<ListNode> node1(new ListNode);
   std:: 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;
 
 
}
 
int main()
{
 
    // test02();
    test03();
    cout<<"hello"<<endl;
 
    // myspace::shared_ptr<int> sp1(new int);
    // myspace::shared_ptr<int> sp2(sp1);
    // myspace::shared_ptr<int> sp3(sp1);
    // myspace::shared_ptr<int> sp4(new int);
    // myspace::shared_ptr<int> sp5(sp4);
    // sp1 = sp2;
    // *sp2 = 3;
 
    system("pause");
    return 0;
}


 

// 解决方案:在引用计数的场景下,把节点中的 _prev 和 _next 改成 weak_ptr 就可以了
// 原理就是, node1->_next = node2; 和 node2->_prev = node1; 时 weak_ptr 的 _next 和
_prev 不会增加 node1 和 node2 的引用计数。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#include<memory>
#include<thread>
 
 
struct ListNode
{
    int _data;
    weak_ptr<ListNode> _next;
    weak_ptr<ListNode> _prev;
 
    ~ListNode(){
        cout<<"~ListNode()"<<endl;
    }
 
 
 
};
 
void test01(){
 
    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;
 
 
}
 
 
 
 
 
 
int main()
{
 
 
test01();
 
 
system("pause");
return 0;
}
运行结果

如果不是 new 出来的对象如何通过智能指针管理呢?其实 shared_ptr 设计了一个删除器来解决这
个问题( ps :删除器这个问题我们了解一下)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#include<memory>
#include<thread>
 
 
struct ListNode
{
    int _data;
    weak_ptr<ListNode> _next;
    weak_ptr<ListNode> _prev;
 
    ~ListNode(){
        cout<<"~ListNode()"<<endl;
    }
 
 
 
};
 
void test01(){
 
    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;
 
 
}
 
 
//仿函数的删除器
template<class T>
struct FreeFunc
{
   void operator()(T* ptr){
    cout<<"free:"<<endl;
    free(ptr);
   }
   
};
 
template<class T>
 
struct  DeleteArrayFunc{
 
    void operator()(T *ptr){
        cout<<"delete[]"<<ptr<<endl;
        delete [] ptr;
    }
 
 
};
struct A{
 
};
 
void test02(){
 
    FreeFunc<int> freeFunc;
    shared_ptr<int> sp1((int *)malloc(4),freeFunc);
 
    DeleteArrayFunc<int> deleteArrayFunc;
    shared_ptr<int> sp2( (int *)malloc(4),deleteArrayFunc);
 
    shared_ptr<A> sp4(new A[10],[](A *p){delete[]p;});
    shared_ptr<FILE> sp5(fopen("test.txt","w"),[](FILE *p){
        fclose(p);
    });
 
 
}
 
 
 
 
 
int main()
{
 
 
// test01();
test02();
 
 
system("pause");
return 0;
}
4.C++11和boost中智能指针的关系
1. C++ 98 中产生了第一个智能指针 auto_ptr.
2. C++ boost 给出了更实用的 scoped_ptr 和 shared_ptr 和 weak_ptr.
3. C++ TR1 ,引入了 shared_ptr 等。不过注意的是 TR1 并不是标准版。
4. C++ 11 ,引入了 unique_ptr 和 shared_ptr 和 weak_ptr 。需要注意的是 unique_ptr 对应 boost
的 scoped_ptr 。并且这些智能指针的实现原理是参考 boost 中的实现的。
————————————————
版权声明:本文为CSDN博主「cat_fish_rain」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cat_fish_rain/article/details/131271337

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值