1. make_shared<T>(args): return a shared_ptr dynamically allocated object of type T. Use args to initialize the object.

shared_ptr<T> p(q): p is a copy of shared_ptr q. Increase the count in q. The pointer in q must be convertable to T.

p = q: p and q are shared_ptr holding pointers that are convertable to one another. Decrease p's reference count, and increase q's count; delete p's existing memory if p's count goes to zero.

p.use_count(): return the number of objects sharing with p. Intended for debug purpose.

2. Ordinarily we use auto to make it easier to define an object to hold the result of make_shared:

auto p1 = make_shared<revector<string>>();
auto p2 = make_shared<int>();
auto p(q); // p and q point to the same object

3. The fact that the shared_ptr class automatically free dynamic objects when they are no longer needed makes it fairly easier to use dynamic memory.

// factory return a shared_ptr pointing to a dynamically allocated object
shared_ptr<Foo> factory(T arg)
{
// process arg as a appropriate
// shared_ptr will take care of deleting the memory
return make_shared<Foo>(arg);
} void use_factory(T arg)
{
shared_ptr<Foo> p = factory(arg);
// use p
} // p goes out of scope. The memory to which p points is automatically free

4.If you put shared_ptrs into a container, you should be sure to erase shared_ptr elements once you no longer need those elements.

Programs tend to use dynamic memory for one of three purpose:

  • They don't know how many object they will need
  • They don't know the precise type of the object they need.
  • They want to share data between serval objects.

So far, the classes we have used allocate resources that exist only as long as the corresponding object

vector<string> v1;
{
vector<string> v2 = {"a", "aa", "bbb"};
v1 = v2; // copies the elements in v2 to v1
} // v2 is deleted, which destroys the elements in v2
// v1 has three new copied elements

Two operators allocate and delete dynamic memory:

  • new: allocates memory
  • delete: frees memory allocated by new.

Use these two operator is more error-prone than using a smart pointer.

A dynamic object managed through a build-in pointer exists until it is explictly deleted

Foo factory(T arg)
{
return new Foo(arg); // caller is responsible for deleting this memory
} void use_factory(T arg)
{
Foo *p = use_factory(arg);
// use p but do not delete it
} p goes out of scope, but the memory to which p points is not freeed.

In this example, p was the only pointer to memory allocated by factory. Once use_factory returns, the program has no way to free the memory. Then memory leak.

There are three common problem with using new and delete to manage dynamic memory:

  • Forgetting to delete memory, which is known as memory leak
  • Using a object after it has been deleted
  • Deleting the same object twice

We should use smart pointers rather than plain pointers

If we do not initialize a smart pointer, it is initialized as a null pointer. We can also initialize a smart pointer from a pointer return from new

shared_ptr<double> p1;
shared_ptr<int> p2(new int());

The smart pointer constructors that take pointers are explict. We can not implictly conver a build-in pointer to a smart pointer.

shared_ptr<int> p1 = new int();    // error
shared_ptr<int> p2(new int()); // ok. use direct initilization

A function that return a shared_ptr cannot implictly return a plian pointer in its return statement

shared_ptr<int> clone(int p)
{
return new int(p); // error
} shared_ptr<int> clone(int p)
{
// ok; explicitly create a shared_ptr from int *
return shared_ptr<int>(new int(p));
}

Don't mix ordinary pointers and smart pointers.

When we bind a shared_ptr to a pain pointer, we give responsibility for that memory to the shared_ptr, and we should no longer use a build-in pointer to access the memory to which the shared_ptr now points.

Don't use get to initilize or assign another smart pointer.

c++ Dynamic Memory (part 1)的更多相关文章

  1. (转) Dynamic memory

      In the programs seen in previous chapters, all memory needs were determined before program executi ...

  2. 论文笔记:Learning Dynamic Memory Networks for Object Tracking

    Learning Dynamic Memory Networks for Object Tracking  ECCV 2018Updated on 2018-08-05 16:36:30 Paper: ...

  3. 动态内存分配(Dynamic memory allocation)

    下面的代码片段的输出是什么?为什么? 解析:这是一道动态内存分配(Dynamic memory allocation)题.    尽管不像非嵌入式计算那么常见,嵌入式系统还是有从堆(heap)中动态分 ...

  4. 从五大结构体,带你掌握鸿蒙轻内核动态内存Dynamic Memory

    摘要:本文带领大家一起剖析了鸿蒙轻内核的动态内存模块的源代码,包含动态内存的结构体.动态内存池初始化.动态内存申请.释放等. 本文分享自华为云社区<鸿蒙轻内核M核源码分析系列九 动态内存Dyna ...

  5. c++ Dynamic Memory (part 2)

    Don't use get to initialize or assign another smart pointer. The code that use the return from get c ...

  6. [Paper翻译]Scalable Lock-Free Dynamic Memory Allocation

    原文: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.87.3870&rep=rep1&type=pdf Abstr ...

  7. C++ storage allocation + Dynamic memory allocation + setting limits + initializer list (1)

    1. 对象的空间在括号开始就已经分配,但是构造在定义对象的时候才会实现,若跳过(譬如goto),到括号结束析构会发生错误,编译会通不过. 2.初始化 1 struct X { int i ; floa ...

  8. 基于神经网络的混合计算(DNC)-Hybrid computing using a NN with dynamic external memory

    前言: DNC可以称为NTM的进一步发展,希望先看看这篇译文,关于NTM的译文:人工机器-NTM-Neutral Turing Machine 基于神经网络的混合计算 Hybrid computing ...

  9. (C/C++) Interview in English. - Memory Allocation/Deallocation.

    Q: What is the difference between new/delete and malloc/free? A: Malloc/free do not know about const ...

随机推荐

  1. 清理 Xcode 10 记录

    1,清理 ~/Library/Developer/CoreSimulator/Devices 说明:该目录存放当前的所有模拟器,每个标识符代表一台机器,清理掉避免存在旧版本的模拟器缓存 执行: 关闭模 ...

  2. python-基础小游戏,人在 江湖飘,哪能不挨刀,我几刀砍死你

    #人在 江湖飘,哪能不挨刀,我几刀砍死你 #规则:5赢4. 4赢3 .3赢2. 2赢1 . 1赢5 #提示:绝对值函数abs #假设:老王和老李 import random import time p ...

  3. activemq的高级特性:消息存储持久化

    activemq的高级特性之消息存储持久化 有基于文件的,数据库的,内存的.默认的是基于文件的,在安装目录/data/kahadb.在conf/activemq.xml文件中. <persist ...

  4. 在vscode中使用webpack中安装的echarts文件失败,dom获取class名,图表不显示

    所有的东西都是新学的,所以遇到了很多问题: (1)首先,在电脑上已经安装了node的情况下, 在npm中安装echarts:npm install echarts --save mac系统在最前面加上 ...

  5. jquery选择器基础

    简单选择器 类 id 元素/标签 * 复合(sel1,sel2)逗号隔开 层次选择器 s1 s2:后代选择器,空格隔开 p>c:子代选择器:不包括孙代及以下 p+next :相邻选择器 p~su ...

  6. laravel5.5源码笔记(六、中间件)

    laravel中的中间件作为一个请求与响应的过滤器,主要分为两个功能. 1.在请求到达控制器层之前进行拦截与过滤,只有通过验证的请求才能到达controller层 2.或者是在controller中运 ...

  7. 如何通过SQL语句写入webshell

    在web应用场景下,经常会碰到SQL注入场景,如页面能够执行SQL语句,那么可能会有直接通过SQL语句写入webshell的风险,常见的phpmyadmin环境下,通过几个语句可以轻松将一句话木马写入 ...

  8. 20155212 2016-2017-2 《Java程序设计》第1周学习总结

    20155212 2016-2017-2 <Java程序设计>第1周学习总结 教材学习内容总结 Chapter 1 Java平台概论 Java一开始就是为了有着有限内存与运算资源的消费型数 ...

  9. # 20155308 2016-2017-2《Java程序设计》课堂实践项目 5月17日

    20155308 2016-2017-2<Java程序设计>课堂实践项目 5/17 本次因为git出现了问题,所以没有按时提交我的代码 问题一 在IDEA中对P145 MathTool.j ...

  10. 【课堂实验】Arrays和String单元测试

    实验内容 在IDEA中以TDD的方式对String类和Arrays类进行学习 测试相关方法的正常,错误和边界情况 String类 charAt split Arrays类 sort binarySea ...