动态内存

动态内存使用的三种原因

  • 程序不知道自己需要多少对象
  • 程序不知道所需对象的准确类型
  • 程序需要在多个对线之间共享数据

    文章目录

    • 动态内存
      • 动态内存使用的三种原因
      • 实例1: Exercise 12.2:
      • Write your own version of the StrBlob class including the const versions of front and back.
      • test
      • Exercise 12.6:
      • Exercise 12.7: Redo the previous exercise, this time using shared_ptr.

定义StrBlob类如下Exercise 12.2

 StrBlob():data(std::make_shared<vector<string>>()) { }StrBlob(std::initializer_list<string> il):data(std::make_shared<vector<string>>(il)) { }

2个构造函数都是用初始化成员列表来初始化data成员,令data指向一个动态分配的vector. 默认构造分配一个空的vector,然后接受一个initializer_list的构造函数通过拷贝列表中的值来初始化vector元素。

如下实例1:所示 check私有工具函数,做索引检查,处理异常参数。

StrBlob 只有一个数据成员,当StrBlob 发生拷贝,赋值或者销毁StrBlob 对象时候,它的shared_ptr成员也会拷贝,赋值或者销毁

拷贝一个shared_ptr会递增其引用计数,当将一个shared_ptr赋值给另外一个shared_ptr时候,等号右边的shared_ptr会递增其引用计数,等号左边的shared_ptr会递减其引用计数

实例1: Exercise 12.2:

Write your own version of the StrBlob class including the const versions of front and back.

#include <vector>
#include <string>
#include <initializer_list>
#include <memory>
#include <exception>using std::vector; using std::string;class StrBlob {
public:using size_type = vector<string>::size_type;StrBlob():data(std::make_shared<vector<string>>()) { }StrBlob(std::initializer_list<string> il):data(std::make_shared<vector<string>>(il)) {}size_type size() const { return data->size(); }bool empty() const { return data->empty(); }void push_back(const string &t) { data->push_back(t); }void pop_back() {check(0, "pop_back on empty StrBlob");data->pop_back();}std::string& front() {check(0, "front on empty StrBlob");return data->front();}std::string& back() {check(0, "back on empty StrBlob");return data->back();}const std::string& front() const {check(0, "front on empty StrBlob");return data->front();}const std::string& back() const {check(0, "back on empty StrBlob");return data->back();}private:void check(size_type i, const string &msg) const {if (i >= data->size()) throw std::out_of_range(msg);}private:std::shared_ptr<vector<string>> data;
};

test

#include "ex12_02.h"
#include <iostream>int main()
{const StrBlob csb{ "hello", "world", "pezy" };StrBlob sb{ "hello", "world", "Mooophy" };std::cout << csb.front() << " " << csb.back() << std::endl;sb.back() = "pezy";std::cout << sb.front() << " " << sb.back() << std::endl;
}

Exercise 12.6:

  • Write a function that returns a dynamically allocated vector of ints.

  • Pass that vector to another function that reads the standard input to give values to the elements.

  • Pass the vector to another function to print the values that were read. Remember to delete the vector at the appropriate time.

#include <iostream>    #include <vector>
using namespace std;auto make_dynamically()
{return new vector<int>{};
}auto populate(vector<int>* vec)
{for (int i = 0; i < 4;i++)vec->push_back(i);return vec;
}auto print(vector<int>* vec) -> std::ostream&
{for (auto i : *vec) std::cout << i << " ";return std::cout;
}int main()
{auto vec = populate(make_dynamically());print(vec) << std::endl;delete vec;getchar();return 0;
}

Exercise 12.7: Redo the previous exercise, this time using shared_ptr.

#include <iostream>   #include <vector>   #include <memory>1
using namespace std;auto make_with_shared_ptr()
{return make_shared<vector<int>>();
}auto populate(shared_ptr<vector<int>> vec)
{for (int i = 0; i < 4; ++i)vec->push_back(i);return vec;
}auto print(shared_ptr<std::vector<int>> vec) -> std::ostream&
{for (auto i : *vec) std::cout << i << " ";return std::cout;
}int main()
{auto vec = populate(make_with_shared_ptr());print(vec) << std::endl;getchar();return 0;
}

【Smart_Point】动态内存与智能指针相关推荐

  1. 2.5w字长文爆肝 C++动态内存与智能指针一篇搞懂!太顶了!!!

    动态内存与智能指针 1.动态内存与智能指针 2.shared_ptr类 2.1.make_shared函数 2.2.shared_ptr的拷贝和赋值 2.3.shared_ptr自动销毁所管理的对象 ...

  2. 【C++ Primer 第5版 笔记】第12章 动态内存与智能指针

    转载:http://blog.csdn.net/wwh578867817/article/details/41866315 第 12 章 动态内存 与 智能指针 静态内存 用来保存:(1)局部stat ...

  3. C++知识点34——动态内存与智能指针

    一.动态内存 动态内存所在的位置在堆区,由程序员手动分配并手动释放,而不像栈内存由系统分配和自动释放 C++通过new运算符为对象在堆上分配内存空间并返回该对象的地址,并用delete运算符销毁对象并 ...

  4. C++ Primer 5th笔记(chap 12 动态内存)智能指针概述

    1. 对象的生存期 内存类型 定义 分配和销毁时机 全局对象 程序启动时分配,程序结束时销毁 静态内存 局部static对象类static数据成员 第一次使用时分配,程序结束时销毁 栈内存 定义在函数 ...

  5. C++相关:动态内存和智能指针

    前言 在C++中,动态内存的管理是通过运算符new和delete来完成的.但使用动态内存很容易出现问题,因为确保在正确的时间释放内存是及其困难的.有时候我们会忘记内存的的释放,这种情况下就会产生内存泄 ...

  6. 12.1 动态内存与智能指针(2)

    今天继续学习12.1节时,从练习12.17中发现了一个问题. 首先摘录教材中的原话--一个unique_ptr"拥有"它所指向的对象.与shared_ptr不同,某个时刻只能有一个 ...

  7. 【Smart_Point】动态内存与智能指针实战:文本查询程序(设计set,map,智能指针的应用)

    文章目录 Cpp读入结构性数组 文本查询程序 文本查询程序本版1 Cpp读入结构性数组 #include<sstream> #include<iostream> #includ ...

  8. 【C++ 语言】智能指针 引入 ( 内存泄漏 | 智能指针简介 | 简单示例 )

    文章目录 I . 智能指针 引入 II . 智能指针 简介 III . 智能指针 简单示例 I . 智能指针 引入 1 . 示例前提 : 定义一个 Student 类 , 之后将该类对象作为智能指针指 ...

  9. 道高一尺 魔高一丈 内存泄漏智能指针

    一.什么是内存泄漏 内存泄漏是指程序中已动态分配的堆内存由于某种原因程序未释放或无法释放,造成系统内存的浪费,导致程序运行速度减慢甚至系统崩溃等严重后果. 内存泄漏主要分为两类: 1. 堆内存泄漏 堆 ...

最新文章

  1. Java入门—输入输出流
  2. 新电脑装win7_微软正式跟Win7系统告别了!国产电脑操作新系统诞生:系统更加美观...
  3. SDOI2018IIIDX
  4. Swing中事件的三种处理方法
  5. 年结 利润分配-未分配利润年结
  6. 每个tabpage中都有一个dategridview_其实每个人都是一个孩子,仅此而已
  7. 程序员爱护自己身体的几点建议
  8. 通过Java Hipster升级Spring Security OAuth和JUnit测试
  9. linux man命令 0-8,Linux命令Man解释:SUDO(8):以root身份执行指令
  10. Android如何缓存你的BITMAP对象
  11. 自动检测技术学习心得体会_公司参加中机建设首届BIM技术应用培训班人员顺利结业...
  12. android微信支付
  13. docker .env文件_基于Docker搭建Nacos集群
  14. 用c语言小游戏代码大全,c语言经典游戏代码
  15. RegCleanPro (微软认证-注册表清理软件)
  16. js 金额格式化 和 转成人民币大写金额形式
  17. Oracle常用sql语法手册
  18. Keil关于.axf文件报错
  19. java操作excel方法_Java实现操作excel表格的方法
  20. 使用ssh对服务器进行登录

热门文章

  1. java现有一个泛型类 提供数组排序功能,java编程思想读书笔记 第十六章 数组
  2. python开发视频播放器_python视频播放器
  3. html默认选定,html默认代码
  4. myeclipse搭建php,MyEclipse常用配置图文教程
  5. 不知道什么时间收集的code
  6. 如何使用标准稳压器输出几百毫伏极低直流电压?
  7. 《本人娶刘亦菲的可行性报告》原文
  8. 【MediaPipe】(1) AI视觉,手部关键点实时跟踪,附python完整代码
  9. c++ 判断文件夹是否存在,不存在则创建(可建多级目录)
  10. CloudCompare基础教程(1)-介绍