浅谈智能指针auto_ptr/shared_ptr/unique_ptr

一.智能指针

1.引入

我们通常使用类似new申请一块空间,交由一个指针指向,假如说最后忘记delete,将会造成内存泄露。而智能指针的出现,就是对这种问题的解决方式,智能指针类似指针,却可以用于管理动态分配的内存。本章所解说的是三种智能指针:

(1)C++98提出,C++11摒弃的auto_ptr
C++11新增的
(2)shared_ptr
(3)unique_ptr
在C++里面,三者都被以模板的形式实现,下面是对智能指针的使用

提示:
(1)智能指针的头文件是#include<memory>
(2)由于unique_ptr和shared_ptr是C++11新增的智能指针,所以编译时需要添加支持C++11的参数
g++ xx.cpp -o xx -std=c++11
(3)智能指针在std域里,需要添加名称空间using namespace std,或者在智能指针前加std::

//test1
#include <iostream>
#include <string>
#include <memory>
using namespace std;

class Report
{
public:
    Report(const std::string s):str(s)
    {
        cout<<"Object created"<<endl;
    }
    ~Report()
    {
        cout<<"Object deleted"<<endl;
    }
    void comment()const
    {
        cout<<str<<endl;
    }
private:
    std::string str;
};

int main(int argc, char* const argv[])
{
    //test1: use smart ptr
    {
        std::auto_ptr<Report> ps(new Report("using auto_ptr"));
        ps->comment();
    }
    {
        std::shared_ptr<Report> ps(new Report("using shared_ptr"));
        ps->comment();
    }
    {
        std::unique_ptr<Report> ps(new Report("using unique_ptr"));
        ps->comment();
    }
    return 0;
}

执行结果

[root@server10 auto_ptr]# ./t 
Object created
using auto_ptr
Object deleted
Object created
using shared_ptr
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值