当前位置:网站首页>06 动态内存
06 动态内存
2022-08-09 03:18:00 【纸境止境】
link: geeksforgeeks
1.申请新的内存
模板:
pointer-variable = new data-type;
以下是使用实例:
int *p = NULL; // 指针初始化为空
p = new int; // 然后对变量索取内存
等价于↓↓↓
int *p = new int;
2.基本数据类型初始化内存
我们可以通过 new 运算符来为int、float等基本的数据类型来初始化内存。如果是自定义的数据类型的话,则需要一个 构造函数 来初始化内存。
int *p = new int(25); //对int类型分配内存
float *q = new float(75.25); //对float类型分配内存
// 自定义的数据类型
struct cust
{
int p;
cust(int q) : p(q) {}
};
cust* var1 = new cust; // Works fine, doesn't require constructor
OR
cust* var1 = new cust(); // Works fine, doesn't require constructor
cust* var = new cust(25) // Notice error if you comment this line
3.数组类型内存初始化
模板:
pointer-variable = new data-tpye[size];
使用实例:
int *p = new int[10];
这句话为 10个int类型的分配内存,然后返回第一个元素的指针给p。
4.数组用 new 或者不用的区别
数组不使用 new 的话,数组就会自动通过编译器销毁(在它所在的函数结束时销毁);而使用 new 的话,数组就不会自动的销毁,而是等待销毁命令才会销毁。
5.删除内存
实例:
delete q; //删除基本变量
delete[] p; //删除数组
当使用 new int[n] 的时候除了,会申请 n 个int类型的字节数,还会在前面额外多申请4个字节来保存 int 的个数。所以,删除的时候一定要配套使用 delete[] ,否则不能读取要删除的个数。
6.当运行的时候,没有足够内存
当没有足够内存的情况下,这个请求就会抛出类型为 std::bad_alloc 的异常指示。除非,将 nothrow 与 new 一起使用,这种情况下,它会返回一个NULL指针。
7、堆内存定义的初始化
int* p1 = new int; //用new开辟了一个新的内存,p 指向它,设置断点跟踪,它的内存没有初始化
int *p2 = new int();//对这个新开的值进行了初始化
//以下同理:
int *p3 = new int[10]();
int *p4 = new string();
这种写法对内置的类型才有意义,自己自定义的类是没有效果的。
边栏推荐
猜你喜欢
随机推荐
win10上运行emwin
A separate machine is connected to the spark cluster of cdh, and the task is submitted remotely (absolutely successful, I have tested it n times)
EventLoop同步异步,宏任务微任务笔记
深度学习——以天气识别为例,探讨如何保存神经网络模型
Win7电脑无法进入睡眠模式?
Exchange VLAN experiment
JSP入门
leetcode-23. Merge K ascending linked lists
C专家编程 第8章 为什么程序员无法分清万圣节和圣诞节 8.10 轻松一下---国际C语言混乱代码大赛
What are the functions and applications of the smart counter control board?
【21天学习挑战赛】二分查找题目之寻找峰值
进程和计划任务管理
2022-08-08 第五小组 顾祥全 学习笔记 day31-集合-IO流-File类
Chapter 2数据分析
VS2019 compiles boost_1_79, generates 32-bit and 64-bit static libraries
5824. 子字符串突变后可能得到的最大整数
开发工程师必备————【Day05】UDP协议;进程的并发与并行
23 Lectures on Disassembly of Multi-merchant Mall System Functions-Platform Distribution Level
Embedded system driver advanced [3] - __ID matching and device tree matching under platform bus driver development
powershell execution strategy









