用过shared_ptr 的不用那么牛叉,http协议居然还分Windows 和Linux,某公司的技术总监我也是服了。还有所谓的研发部经理,你们公司作为20多年的小公司,研发出来啥啦?还大嘴巴一张“JSON”你难道还不知道吗?我心说你“是不是傻叉,牛逼个啥!”
没有用过的看过来,这个入门非常好。
// sharedptr1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
int main()
{
//two shared pointers representing two persons by their name
shared_ptr<string> pNico(new string("nico"));
shared_ptr<string> pJutta(new string("jutta"));
//初始化的时候也可以使用 便捷函数 make_shared()
shared_ptr<string> pNico2 = make_shared<string>("noco2");
shared_ptr<string> pJutta2 = make_shared<string>("jutta2");
//初始化的时候也可以使用 reset():
shared_ptr<string> pNico4;
// pNico4 = new string("Nico4");//这么写就错了
pNico4.reset(new string("Nico4"));//OK
//capital person names
// (*pNico)[0] = 'N';// this line code it does not work so ,do it like pJutta
pNico->replace(0, 1, "N");
pJutta->replace(0,1,"J");//将开始处:0 一直到结束处:1 替换为 J 说白了就是替换了首字符
//put them multiple times in a container
vector<shared_ptr<string>> whoMadeCoffee;
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pNico);
whoMadeCoffee.push_back(pJutta);
whoMadeCoffee.push_back(pNico);
//print
for (auto ptr: whoMadeCoffee)
{
cout << *ptr <<" ";
}
cout << endl;
//overwirte a name again
*pNico = "NicolaisZhaoSi";
cout << "***After Overwrit***" << endl;
//print again
for (auto ptr : whoMadeCoffee)
{
cout << *ptr <<" ";
}
cout << endl;
//print some internal data
cout << "use_count of pJutta:" << whoMadeCoffee[0].use_count() << endl;
cout << "use_count of pJutta:" << whoMadeCoffee[2].use_count() << endl;
}
程序解释:shared_ptr 可以共享(或者说拥有)同一对象。对象的最后一个拥有者有责任销毁对象,并清理与该对象相关的所有资源。
总之,shared_ptr的目标就是在其所指向的对象不再被需要之后,自动释放与对象相关的资源。
可以像使用任何其他pointer一样地使用shared_ptr。可以赋值、拷贝、比较他们。下面解释一下上面程序的要点:
#include <memory> 需要包含这个文件。
声明和赋初值的时候有三种写法,{}、reset()、make_shared() 都可以,哪种都可以。
但凡是容器,总是为传入的元素创建属于容器自己的拷贝,所以如果我们直接插入string,插入的其实是string 的拷贝。我们放进去的是一个poiner to string ,因此被复制的也是那些pointer ,于是容器内含有多个“指向同一对象”的reference。这意味着如果我们改动对象,该容器内的所有身影(occurrence)都会被改动。
use_count()会返回某个shared_ptr所指对象的当前拥有者的数量。
运行结果如下:
Jutta Jutta Nico Jutta Nico
***After Overwrit***
Jutta Jutta NicolaisZhaoSi Jutta NicolaisZhaoSi
use_count of pJutta:4
use_count of pJutta:3