初探C++智能指针

见过太多用智能指针的代码了,并且自我感觉自己指针的基础还可以,模板类这块也在反复横跳,左右试探。。。所以来肝智能指针了。主要参考书籍还是C++ Primer第16章和第18章。


智能指针三剑客:auto_ptr、unique_ptr、shared_ptr、weak_ptr。第一个是c++98提供的,后两个是c++11提供的,推荐用后三个。智能指针的作用简单粗暴点来讲就是封装指针成类,让系统帮你管理内存,自我感觉类似C#的GC机制。这篇博客假设读者已经有基本的指针、模板类知识储备。

话不多说直接上代码,通过这段代码可以管中窥豹,看到智能指针的基本思想:

#include <iostream>

template<typename T>
class Auto_ptr1
{
public:
	Auto_ptr1(T* ptr = nullptr) :m_ptr{ ptr } {}

	virtual ~Auto_ptr1()
	{
		delete m_ptr;
	}

    //操作符重载
	T& operator*() { return *m_ptr; }
	T* operator->() { return m_ptr; }

private:
	T* m_ptr;
};


int main()
{
	system("pause");
	return 0;
}

看懂了吗?没看懂没关系,接下来是分析:

ok,智能指针基本原理已经懂了,接下来看看怎么用:

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

class Report
{
private:
    string str;
    int a;
public:
    Report(const string s):str(s)
    {
        cout << "Object created!\n";
    }
    ~Report()
    {
        cout << "Object deleted!\n";
    }
    void comment() const { cout << str << a << "\n"; }
};

int main()
{

    //去掉{}你会发现没有输出delete的过程了
    {
        auto_ptr<Report> ps(new Report("using auto_ptr"));
        ps->comment();
    }

    {
        shared_ptr<Report> ps(new Report("using shared_ptr"));
        ps->comment();
    }
    {
        unique_ptr<Report> ps(new Report("using unique_ptr"));
        ps->comment();
    }
    system("pause");
    return 0;
}

更改一下如下:

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

class Report
{
private:
    string str;
    int a;
public:
    Report(const string s):str(s)
    {
        cout << "Object created!\n";
    }
    ~Report()
    {
        cout << "Object deleted!\n";
    }
    void comment() const { cout << str << a << "\n"; }
};

int main()
{
    auto_ptr<Report> ps(new Report("using auto_ptr"));
    ps->comment();


    shared_ptr<Report> pd(new Report("using shared_ptr"));
    pd->comment();

    unique_ptr<Report> pe(new Report("using unique_ptr"));
    pe->comment();
    
    system("pause");
    return 0;
}

输出:

为啥,因为这些智能指针在main函数作用域下,是等程序结束的时候,系统才会调用析构函数,所以黑窗口肯定看不到啦。

ok,继续再看一个视觉上有点复杂的例子:

#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
using namespace std;

unique_ptr<int> make_int(int n)
{
    return unique_ptr<int>(new int(n));
}
void show(unique_ptr<int>& pi)
{
    cout << *pi << " ";
}

int main()
{
    vector<unique_ptr<int>> vp(5);
    for (int i = 0; i < vp.size(); i++)
    {
        vp[i] = make_int((rand() % 1000));
    }
    vp.push_back(make_int(rand() % 1000));
    for_each(vp.begin(), vp.end(), show);

    system("pause");
    return 0;

}

看懂了吗?没有的话,分析如下:

好了暂时到这里。果然看多了会发现C++ Primer真的只适合入门。。。好想看源码。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

keneyr

老爷~给小的赏点盘缠吧555~

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

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

打赏作者

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

抵扣说明:

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

余额充值