栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【跟着于老师学C/C++】5.4 allocate-merrory-c++style

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【跟着于老师学C/C++】5.4 allocate-merrory-c++style

1 前言

突发奇想,记录下来,一来纪念,纪念这段有目标有方向的路,二来自己复习用。

2 视频链接

视频连接点这

3 operator 操作符 new and new[] C 和C++内存管理的区别

C : malloc free

  • 仅仅是申请一段内存,然后将指针返回。
    c++:
  • 不仅仅是申请一段内存。
3.1 C++内存申请
//allocate an int, default initializer(do nothing)
int * p1 = new int;

new是操作符,new int是表达式,结果是内存的地址。

初始化,可以理解为默认的初始化,对于new int的初始化为啥都不干,初始化了个寂寞啊。

//allocate an int, initialized to 0
int * p2 = new int();

初始化0。

//allocate an int, initialized to 5
int * p3 = new int(5);

初始化为5.

更复杂的。(更复杂的功能后面会介绍)

//allocate an int, initialized to 0
int * p4 = new int{};//c++11
//allocate an int, initialized to 5
int * p5 = new int{5};//c++11

看看怎么初始化结构体的。C++中的结构体和类几乎完全等价。

//allocate a Student class, default initializer
Student * ps1 = new Student;
//allocate a Student class, initialize the members
Student * ps2 = new Studeng{"Yu", 2020, 1};//c++11 

? class中的默认初始化是怎么错的。?(后面再来回答)

数组
//allocate 16 int, default initializer(do nothing)
int * pa1 = new int[16];
//allocate 16 int, zero initialized
int * pa2 = new int[16]();
//allocate 16 int, zero initialized
int * pa3 = new int[16]{};//c++11
//allocate 16 int, the first 3 elements are initialized to 1,2,3, the rest 0
int * pa4 = new int[16]{1, 2, 3};

//allocate memory for 16 Student objects, default initializer
Student * psa1 = new Student[16];
//allocate memory for 16 Student objects, the first two elements are initialized
Student * psa2 = new Student[16]{{"Shao",1989,1},{"Nian", 1990,2}};

为类成员数组申请内存,会调用类成员默认的初始化

3.2 操作符delete和delete[]
//deallocate memory
delete p1;
//deallocate memory
delete ps1;

//deallocate the memory of the array
delete pa1;
//deallocate the memory of the array
delete []pa2;

//deallocate the memory of the array, and call the destructor of the first element
delete pa1;
//deallocate the memory of the array, and call the destructors of all the elements
delete []psa2;

[]的区别,

  • 如果是int数组,delete 和delete[]是没有区别的,但是对于结构体数组,就有区别了。都会释放掉内存,但是delete只会调用第一个元素的析构函数,delete []会调用所有元素的析构函数。
  • **只要是数组,就写成delete [] 最安全 **。
4 conclusion
  • Operateor new is similar with malloc() but with more features
  • …
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1025352.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号