c++中的智能指针

智能指针的原理就是将动态分配的内存块与一个或多个智能指针对象相关联,以确保内存块在不再需要时能够自动释放。通常情况下,智能指针会将内存的所有权转移到其自己的对象中,并在其析构函数中释放内存。这样就可以避免常见的内存泄漏和释放非法内存等问题。

1.unique_ptr 独占指针

当内存超出作用域就自动释放

不可copy,只能move

unique_ptr可以指向一个数组。

unique_ptr需要确定删除器的类型。

#include <memory>

int  main(){  
    std::unique_ptr<int>a(new int());
    std::unique_ptr<int>b(a);
    return 0 ;
}
#include <memory>

int  main(){  
    std::unique_ptr<int>a(new int());
    std::unique_ptr<int>b=std::move(a);
    return 0 ;
}

防拷贝,因此也叫做唯一指针
直接把拷贝构造给删了。同样赋值重载也是一样被删了。

2.shared_ptr 共享指针

std::shared_ptr使用引用计数,每一个shared_ptr的拷贝都指向相同的内存。在最后一个shared_ptr析构的时候,内存才会被释放。
sharedd_ptr共享被管理的对象,同一时刻可以有多个shared_ptr拥有对象的所有权,当最后一个shared_ptr对象销毁时,被管理对象自动销毁。
shared_ptr实现包含了两个部分:
(1)一个指向堆上创建的对象的裸指针 raw_ptr。
(2)一个指向内部隐藏的、共享的管理对象 shared_count_object。其中use_count是当前这个堆上对象被多少对象引用了,简单来说就是引用计数。
1.使用智能指针可以自动释放占用的内存。
#include <memory>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int  main(){  
    std::shared_ptr<int>a(new int(0));
    std::shared_ptr<int>b(a);
    ++(*a),++(*b);
    ++(*a);
    std::cout<<(*a)<<" "<<(*b)<<endl;
    return 0 ;
}
2)共享所有权指针的传播和释放
(3)s.use_count():返回shared_ptr的强引用计数
#include <memory>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int  main(){  
    std::shared_ptr<int>a(new int(0));
    std::shared_ptr<int>b(a);

    cout<<a.use_count()<<endl;
    std::shared_ptr<int>c(b);
    cout<<a.use_count()<<endl;
    return 0 ;
}
(4)s.unique():若use_count为1返回true,否则返回false
#include <memory>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int  main(){  
    std::shared_ptr<int>a(new int(0));
    std::shared_ptr<int>b(a);

    cout<<a.use_count()<<endl;
    std::shared_ptr<int>c(b);
    cout<<a.use_count()<<endl;
    cout<<a.unique()<<endl;
    return 0 ;
}

3.weak_ptr

weak_ptr 可以指向资源,访问资源,不参与资源的管理也就是不增加引用计数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多年以后

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值