智能指针的简单分析(一)

  1. unique_ptr 一份数据只允许一个控制权

    struct StNode
    {
        int a;
        string str;
        StNode(int x = 0, string s = "") : a(x), str(s) {};
        ~StNode() {};
    };
    void Print_Unique_Ptr_B(std::unique_ptr<StNode> ptr)
    {
        cout << "Print_Unique_Ptr_B :" << "\n"
            << "a = " << ptr->a << "\n"
            << "str = " << ptr->str << endl;
    }
    void Print_Unique_Ptr_A(std::unique_ptr<StNode> ptr)
    {
        cout <<"Print_Unique_Ptr_A :" << "\n"
             << "a = " << ptr->a << "\n"
             << "str = " << ptr->str << endl;
        Print_Unique_Ptr_B(std::move(ptr));
    }
    void Use_UniquePtr()
    {
        std::unique_ptr<StNode> uptr(new StNode(10, "this"));// 一份数据只允许一个控制权
        Print_Unique_Ptr_A(std::move(uptr));
        if (!uptr)
        {
            cout << "uptr is nullptr" << endl;
        }
    }
    
  2. shared_ptr 多个地方,共享同一份数据

    struct StNode
    {
        int a;
        string str;
        StNode(int x = 0, string s = "") : a(x), str(s) {};
        ~StNode() {};
    };
    void Print_Shared_Ptr_A(std::shared_ptr<StNode> ptr)
    {
        cout << "Print_Shared_Ptr_A :" << "\n"
            << "a = " << ptr->a << "\n"
            << "str = " << ptr->str << endl;
    }
    void Print_Shared_Ptr_B(std::shared_ptr<StNode> ptr)
    {
        cout << "Print_Shared_Ptr_B :" << "\n"
            << "a = " << ptr->a << "\n"
            << "str = " << ptr->str << endl;
    }
    void Use_SharedPtr()
    {
        std::shared_ptr<StNode> spTest = std::make_shared<StNode>(140, "SharedPtr");//多个地方,共享同一份数据
        Print_Shared_Ptr_A(spTest);
        Print_Shared_Ptr_B(spTest);
    }
    

    3、weak_ptr配合shared_ptr使用,解决A持有shared_ptr<B> pb,B持有shared_ptr<A> pa, 导致A、B资源不能释放的问题

    class CB;
    class CA
    {
    public:
        std::shared_ptr<CB> pb_;//调整为 std::weak_ptr<CB> pb_,看下效果
        ~CA()
        {
            cout << "A delete\n";
        }
    };
    class CB
    {
    public:
        shared_ptr<CA> pa_;
        ~CB()
        {
            cout << "B delete\n";
        }
    };
    void fun()
    {
        shared_ptr<CB> pb(new CB()); 
        shared_ptr<CA> pa(new CA());
        pb->pa_ = pa;
        pa->pb_ = pb;
        cout << pb.use_count() << endl;
        cout << pa.use_count() << endl;
    }
    

    https://www.cnblogs.com/TenosDoIt/p/3456704.html这篇文章讲的挺详细的,如果还有疑惑可以点击传送门。

猜你喜欢

转载自blog.csdn.net/chicaidecaiji/article/details/81067006