c++ Dynamic Memory (part 1)
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)的更多相关文章
- (转) Dynamic memory
In the programs seen in previous chapters, all memory needs were determined before program executi ...
- 论文笔记:Learning Dynamic Memory Networks for Object Tracking
Learning Dynamic Memory Networks for Object Tracking ECCV 2018Updated on 2018-08-05 16:36:30 Paper: ...
- 动态内存分配(Dynamic memory allocation)
下面的代码片段的输出是什么?为什么? 解析:这是一道动态内存分配(Dynamic memory allocation)题. 尽管不像非嵌入式计算那么常见,嵌入式系统还是有从堆(heap)中动态分 ...
- 从五大结构体,带你掌握鸿蒙轻内核动态内存Dynamic Memory
摘要:本文带领大家一起剖析了鸿蒙轻内核的动态内存模块的源代码,包含动态内存的结构体.动态内存池初始化.动态内存申请.释放等. 本文分享自华为云社区<鸿蒙轻内核M核源码分析系列九 动态内存Dyna ...
- 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 ...
- [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 ...
- C++ storage allocation + Dynamic memory allocation + setting limits + initializer list (1)
1. 对象的空间在括号开始就已经分配,但是构造在定义对象的时候才会实现,若跳过(譬如goto),到括号结束析构会发生错误,编译会通不过. 2.初始化 1 struct X { int i ; floa ...
- 基于神经网络的混合计算(DNC)-Hybrid computing using a NN with dynamic external memory
前言: DNC可以称为NTM的进一步发展,希望先看看这篇译文,关于NTM的译文:人工机器-NTM-Neutral Turing Machine 基于神经网络的混合计算 Hybrid computing ...
- (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 ...
随机推荐
- Oracle AWR与警报系统一
管理自动工作负荷知识库 Oracle收集大量有关性能和活动的统计信息.这些信息在内存中积累,并定期写入数据库:写入到构成自动工作负荷知识库(Automatic Workload Repository, ...
- Xcode 创建 支持IOS4.3以上版本的应用的方法
如果是Xcode 5的话步骤为 点击项目名称->Build Settings->搜索 Architectures 这个里面的原始的值是Standard architectures(armv ...
- 需求:promise执行买菜做饭过程
需求:promise执行买菜做饭过程 1.买菜 2.洗菜 3.做饭 4.吃饭 <!DOCTYPE html> <html lang="en"> <he ...
- iOS 12.0-12.1.2 越狱教程
unc0ver V3.0.0~b29 越狱工具已经开始公测,支持搭载 A8X-A11 处理器的 iOS 12.0-12.1.2 设备完整越狱,Cydia 商店和 Substrate 插件可正常安装并运 ...
- table的td、th的一些样式问题(宽度,边框,滚动条)
1. 给table加边框 table{ border-collapse: collapse; /*表格的边框合并为一个单一的边框*/ } table, table tr th, table tr td ...
- Dynamics CRM 常用的JS
常用JS(一) Xrm.Page.context.getUserId(): //获取当前用户id Xrm.Page.context.getUserName(): //获取当前用 ...
- 接口测试jemeter使用
使用jemeter5时要先添加环境变量,需要有JDK1.8及以上版本支持.这里主要对接口测试做一些说明. 以上就是常见的设置问题.在window上我们通常是不需要改动配置文件的,如果要在生产上执行测试 ...
- python 时间time模块介绍和应用
1.其中format_string 类型的时间和struct_time之间可以转换,timestamp时间戳可以和struct_time之间进行转化,但是时间戳和格式化时间是不能直接转换的. time ...
- 最短寻道优先算法(SSTF)——磁盘调度管理
原创 最近操作系统实习,敲了实现最短寻道优先(SSTF)——磁盘调度管理的代码. 题目阐述如下: 设计五:磁盘调度管理 设计目的: 加深对请求磁盘调度管理实现原理的理解,掌握磁盘调度算法. 设计内容: ...
- git如何到精通
git教程 目录 一.版本控制概要 1.1.什么是版本控制 1.2.常用术语 1.3.常见的版本控制器 1.4.版本控制分类 1.4.1.本地版本控制 1.4.2.集中版本控制 1.4.3.分布式 ...