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
- …