C++智能指针

本文介绍了C++中的智能指针,包括其分类和作用,如解决野指针、内存泄漏问题。重点讲解了、的区别,以及在解决循环引用问题上的策略。并提到了使用智能指针的一些最佳实践,如Effective C++和Effective Modern C++中的相关条款,强调了智能指针在防止内存泄漏中的重要性。
摘要由CSDN通过智能技术生成


指针的危害

  • 指针未初始化
  • 野指针
  • 内存泄漏

0.智能指针分类

在这里插入图片描述

  • 本质:
    将指针封装为类对象成员,并在析构函数里删除指针指向的内存
  • 不同:
    auto_ptrunique_ptrscoped_ptr马上删除。
    shared_ptr计数为0删除。
    weak_ptr不删除。

智能指针是来解决指针危害的。

1. auto_ptr

  • 作用
    对作用域内的动态分配对象的自动释放
  • 基本类型
#include <iostream>
#include <memory>
using namespace std;
int main(){
   
    int* pn = new int(10);
    auto_ptr<int> ap(pn);
    cout << *ap << endl;
}
  • 类类型
#include <iostream>
#include <memory>
using namespace std;
class Test{
   
public:
    Test(){
   cout << __func__ << endl;}
    ~Test(){
   cout << __func__ << endl;}
    void Func(){
   cout << __func__ << endl;}
};
int main(){
   
    Test* pt = new Test;
    auto_ptr<Test> apt(pt);
    apt->Func();
}

通过valgrind可以看到没有内存泄露,指针可以被正常释放。

  • 缺陷
  1. 两个auto_ptr不能同时拥有同一个对象
#include <memory>
using namespace std;
int main(){
   
    int* pn = new int(10);
    auto_ptr<int> ap1(pn);
    auto_ptr<int> ap2(pn);
}
  1. auto_ptr不能管理数组指针
#include <memory>
using namespace std;
int main(){
   
    int*pa=new int[10];
    auto_ptr<int>ap(pa);
}
  1. auto_ptr被拷贝或被赋值后,失去对原指针的管理.这种情况被称为指针所有权传递。
  • 赋值的情况
#include <iostream>
#include <memory>
using namespace std;
int main(){
   
    int*p = new int(10);
    auto_ptr<int> ap1(p);
    cout<< *ap1 <<endl;
    auto_ptr<int> ap2=ap1;
    cout
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值