见过太多用智能指针的代码了,并且自我感觉自己指针的基础还可以,模板类这块也在反复横跳,左右试探。。。所以来肝智能指针了。主要参考书籍还是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真的只适合入门。。。好想看源码。。