【跟着于老师学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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值