【C++学习笔记】十一、智能指针的简单使用

文章目录

1 智能指针

智能指针相对于传统的指针来说只有好处没有坏处,更好的管理内存,可以在引用计数为0的时候,自己去析构,释放内存。
智能指针在离开其作用域后会自动销毁释放。
我们实际开发中一般用如下两种方式去构建。

2 构造

第一种是配合make_shared去申请
第二种直接new

    shared_ptr<int>  p1 = std::make_shared<int> (1);
    shared_ptr<int>  p2 (new int(2));

    cout << "p1=" << *p1 << endl;
    cout << "p2=" << *p2 << endl;

实际使用起来和普通指针的差别不大。
打印引用次数

    cout << "p1 cout =" << p1.use_count() << endl;

打印结果为1

实际稍微复杂点的demo


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

using namespace std;

class user
{
    
    
public:
    user()
    {
    
    

    };
    user(string _name,int _type)
    {
    
    
       name = _name;
       type = _type;
    };
    ~user()
    {
    
    

    };
   string name = "user1";
   int type = 1;
};


int main()
{
    
    
    shared_ptr<user>  p1 = std::make_shared<user> ("help",2);

    cout << "p1=" << p1->name << "\t" << p1->type << endl;

    return 0;
}

上述的情况下引用计数都为1,每当我们对一个智能指针进行一次拷贝,其引用计数会+1.

    shared_ptr<int>  p1 = std::make_shared<int> (2);
    cout << "cout="<<p1.use_count() << endl;
    shared_ptr<int>  p2(p1);
    cout << "cout="<<p2.use_count() << endl;

打印出的结果为

cout=1
cout=2

猜你喜欢

转载自blog.csdn.net/qq_38753749/article/details/130226532