追加一个shared_ptr指针

#include <memory>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
//===========================
// 错误 两个只能指针 管理一个已经分配的内存
//int* p = new int(7);
//shared_ptr<int> p1(p);
//shared_ptr<int> p2(p);
//============================ //================================
// 正确做法
shared_ptr<int> sp1(new int());
shared_ptr<int> sp2(sp1); //
//================================ return ;
}

weak_ptr示例

/*
// 使用shred_ptr的主要原因就是避免关注指针指向的资源
// 只能指针将自动释放与不再需要的对象的相关资源
// 但是某些情况下,这种却不是我们需要的。
// 比如 循环引用.两个对象都引用对方。
// 又或者 分享一个对象 但是不占有该对象
// 这个时候可以使用weak_ptr 其实相对shared_ptr 该指针不增加计数
//
*/ #include <iostream>
#include <string>
#include <vector>
#include <memory> using namespace std; class Person{
public:
string name;
shared_ptr<Person> mother;
shared_ptr<Person> father;
vector<shared_ptr<Person>> kids; Person(const string& n,
shared_ptr<Person> m = nullptr,
shared_ptr<Person> f = nullptr)
:name(n), mother(m), father(f){
} ~Person(){
cout << "delete " << name << endl;
}
}; shared_ptr<Person> initFamily(const string& name)
{
shared_ptr<Person> mom(new Person(name + "'s mom"));
shared_ptr<Person> dad(new Person(name + "'s dad"));
shared_ptr<Person> kid(new Person(name,mom,dad));
mom->kids.push_back(kid);
dad->kids.push_back(kid);
return kid;
} int _tmain(int argc, _TCHAR* argv[])
{
shared_ptr<Person> p = initFamily("nico"); cout << "nico's family exists" << endl;
cout << "- nico is shared " << p.use_count() << " times" << endl;
cout << "- name of 1st kid of nico's mom: "
<< p->mother->kids[]->name << endl; p = initFamily("jim");
cout << "jim's family exists" << endl; return ;
}

运行代码结果如下:

nico's family exists
- nico is shared 3 times
- name of 1st kid of nico's mom: nico
jim's family exists
请按任意键继续. . .

实际上我们并没有看到 指针指向资源的释放 这是因为在class Person 中的vector中 使用了shared_ptr 指针增加了资源的计数 所以没有及时释放

我们应该将vector这个容器改为weak_ptr  同时在使用上 weak_ptr 需要使用lock() 函数将其提升为shared_ptr

/*
// 使用shred_ptr的主要原因就是避免关注指针指向的资源
// 只能指针将自动释放与不再需要的对象的相关资源
// 但是某些情况下,这种却不是我们需要的。
// 比如 循环引用.两个对象都引用对方。
// 又或者 分享一个对象 但是不占有该对象
// 这个时候可以使用weak_ptr 其实相对shared_ptr 该指针不增加计数
//
*/ #include <iostream>
#include <string>
#include <vector>
#include <memory> using namespace std; class Person {
public:
string name;
shared_ptr<Person> mother;
shared_ptr<Person> father;
vector<weak_ptr<Person>> kids; //weakpointer!!!
Person(const string& n,
shared_ptr<Person> m = nullptr,
shared_ptr<Person> f = nullptr)
: name(n), mother(m), father(f) {
}
~Person() {
cout << "delete " << name << endl;
}
}; shared_ptr<Person> initFamily(const string& name)
{
shared_ptr<Person> mom(new Person(name + "'s mom"));
shared_ptr<Person> dad(new Person(name + "'s dad"));
shared_ptr<Person> kid(new Person(name,mom,dad));
mom->kids.push_back(kid);
dad->kids.push_back(kid);
return kid;
} int _tmain(int argc, _TCHAR* argv[])
{
shared_ptr<Person> p = initFamily("nico"); cout << "nico's family exists" << endl;
cout << "- nico is shared " << p.use_count() << " times" << endl;
cout << "- name of 1st kid of nico's mom: "
<< p->mother->kids[].lock()->name << endl; p = initFamily("jim");
cout << "jim's family exists" << endl; return ;
}

运行结果如下

nico's family exists
- nico is shared 1 times
- name of 1st kid of nico's mom: nico
delete nico
delete nico's dad
delete nico's mom
jim's family exists
delete jim
delete jim's dad
delete jim's mom
请按任意键继续. . .

可以看到 资源正确释放

代码 改编自 C++标准库——自学教程与参考手册 英文第二版

c++智能指针(2)的更多相关文章

  1. enote笔记法使用范例(2)——指针(1)智能指针

    要知道什么是智能指针,首先了解什么称为 “资源分配即初始化” what RAII:RAII—Resource Acquisition Is Initialization,即“资源分配即初始化” 在&l ...

  2. C++11 shared_ptr 智能指针 的使用,避免内存泄露

    多线程程序经常会遇到在某个线程A创建了一个对象,这个对象需要在线程B使用, 在没有shared_ptr时,因为线程A,B结束时间不确定,即在A或B线程先释放这个对象都有可能造成另一个线程崩溃, 所以为 ...

  3. C++智能指针

    引用计数技术及智能指针的简单实现 基础对象类 class Point { public: Point(int xVal = 0, int yVal = 0) : x(xVal), y(yVal) { ...

  4. EC笔记:第三部分:17、使用独立的语句将newed对象放入智能指针

    一般的智能指针都是通过一个普通指针来初始化,所以很容易写出以下的代码: #include <iostream> using namespace std; int func1(){ //返回 ...

  5. 智能指针shared_ptr的用法

    为了解决C++内存泄漏的问题,C++11引入了智能指针(Smart Pointer). 智能指针的原理是,接受一个申请好的内存地址,构造一个保存在栈上的智能指针对象,当程序退出栈的作用域范围后,由于栈 ...

  6. 智能指针unique_ptr的用法

    unique_ptr是独占型的智能指针,它不允许其他的智能指针共享其内部的指针,不允许通过赋值将一个unique_ptr赋值给另一个unique_ptr,如下面错误用法: std::unique_pt ...

  7. 基于C/S架构的3D对战网络游戏C++框架 _05搭建系统开发环境与Boost智能指针、内存池初步了解

    本系列博客主要是以对战游戏为背景介绍3D对战网络游戏常用的开发技术以及C++高级编程技巧,有了这些知识,就可以开发出中小型游戏项目或3D工业仿真项目. 笔者将分为以下三个部分向大家介绍(每日更新): ...

  8. C++ 引用计数技术及智能指针的简单实现

    一直以来都对智能指针一知半解,看C++Primer中也讲的不够清晰明白(大概是我功力不够吧).最近花了点时间认真看了智能指针,特地来写这篇文章. 1.智能指针是什么 简单来说,智能指针是一个类,它对普 ...

  9. C++11智能指针读书笔记;

    智能指针是一个类对象,而非一个指针对象. 原始指针:通过new建立的*指针 智能指针:通过智能指针关键字(unique_ptr, shared_ptr ,weak_ptr)建立的指针 它的一种通用实现 ...

  10. 「C++」理解智能指针

    维基百科上面对于「智能指针」是这样描述的: 智能指针(英语:Smart pointer)是一种抽象的数据类型.在程序设计中,它通常是经由类型模板(class template)来实做,借由模板(tem ...

随机推荐

  1. 设计table表格,用js设计偶数行和奇数行显示不同的颜色

    第一种:鼠标经过时table表格中的颜色根据奇偶行改变不同的颜色 <!DOCTYPE html> <html> <head> <meta charset=&q ...

  2. sql数据库之多库查询

    连接到数据库服务器gwsps07上,打开查询分析器,如何获取gwrenshi数据库中的数据? 查询语句如下: select * from GWRENSHI.CGC.dbo.PERempms(serve ...

  3. STL::unordered_map/unordered_multimap

    unordered_map: 和 unorder_set 相似,该容器内部同样根据 hash value 把键值对存放到相应的 bucket(slot)中,根据单个 key 来访问 value 的速度 ...

  4. numpy 之矩阵的认知

    di numpy 矩阵的创建与应用 可以用np.mat(a) 将a转变成矩阵 矩阵的加减法和 array相同 矩阵的乘法,如果矩阵要相乘的话就要A矩阵的行数,和B矩阵的列数相同才可以 这是查看数组不重 ...

  5. JMeter快速入门之Badboy录制

    1. 前言 JMeter录制有两种方式,一种是JMeter自带录制方法,另一种是下面要学习的Badboy录制,个人推荐使用此方法 下面教程不设计Badboy安装,可以百度一下. 2. 录制步骤: 2. ...

  6. java深拷贝与浅拷贝

    1.调用Object类的clone方法必须实现Cloneable接口,clone属于浅拷贝. 2.可以通过java的反序列化机制进行深拷贝. 3.可以直接用apache提供的一些包进行深拷贝和浅拷贝, ...

  7. vue项目引入FastClick组件解决IOS系统下h5页面中的按钮点击延迟,连续点击无反应的问题

    异常描述: ios系统手机中访问h5页面,按钮点击有延迟,连续点击卡顿.无反应. 异常原因: 这要追溯至 2007 年初.苹果公司在发布首款 iPhone 前夕,遇到一个问题:当时的网站都是为大屏幕设 ...

  8. vue params和query传参区别

    参考地址:https://blog.csdn.net/bluefish_flying/article/details/81011230 router.js中 路由设置这里, 当你使用params方法传 ...

  9. mybatis插入数据并获取主键值

    有时候我们的主键是自增的,但是我们想要在插入一条数据以后获取这条数据的主键值,而我们知道,mybatis执行完插入操作以后返回的是生效的记录数.那如何才能获取这个主键值呢. 1.在配置文件mapper ...

  10. 开机进入boot menu和application menu,无法开机

        1.开机点击F1进入到bios界面 2.进入Security—Secure Boot—Disabled 如果不修改Secure boot选项为Disabled,在光驱引导时可能会出现报错 3. ...