目录
4.operator new 与operator delete 函数
6.malloc/free 与 new/delete 的区别
首先我们需要了解一下数据在内存中的分布,请看以下代码:
- int globalVar = 1;
- static int staticGlobalVar = 1;
-
- void Test()
- {
- static int staticVar = 1;
- int localVar = 1;
-
- int num1[10] = { 1, 2, 3, 4 };
-
- char char2[] = "abcd";
- const char* pChar3 = "abcd";
-
- int* ptr1 = (int*)malloc(sizeof(int) * 4);
- int* ptr2 = (int*)calloc(4, sizeof(int));
- int* ptr3 = (int*)realloc(ptr2, sizeof(int) * 4);
- free(ptr1);
- free(ptr3);
- }

malloc / calloc / realloc / free :详情可参考c语言动态内存管理函数
面试题:
- void Test()
- {
- // 动态申请一个int类型的空间
- int* ptr4 = new int;
-
- // 动态申请一个int类型的空间并初始化为10
- int* ptr5 = new int(10);
-
- // 动态申请10个int类型的空间
- int* ptr6 = new int[3];
- delete ptr4;
- delete ptr5;
- delete[] ptr6;
- }

- class A
- {
- public:
-
- A(int a = 0)
- : _a(a)
- {
- cout << "A():" << this << endl;
- }
-
- ~A()
- {
- cout << "~A():" << this << endl;
- }
-
- private:
- int _a;
- };
-
- int main()
- {
- // new/delete 和 malloc/free最大区别是 new/delete对于【自定义类型】除了开空间还会调用构造函数和析构函数
-
- A* p1 = (A*)malloc(sizeof(A));
- A* p2 = new A(1);
- free(p1);
- delete p2;
-
- // 内置类型是几乎是一样的
- int* p3 = (int*)malloc(sizeof(int)); // C
- int* p4 = new int;
- free(p3);
- delete p4;
-
- A* p5 = (A*)malloc(sizeof(A)*10);
- A* p6 = new A[10];
- free(p5);
- delete[] p6;
-
- return 0;
- }
4.operator new 与operator delete 函数
总结:new 的底层是operator new ,operator new 是 malloc 的封装
- class A
- {
- public:
- A(int a = 0)
- : _a(a)
- {
- cout << "A():" << this << endl;
- }
- ~A()
- {
- cout << "~A():" << this << endl;
- }
- private:
- int _a;
- };
-
- // 定位new/replacement new
- int main()
- {
- // p1现在指向的只不过是与A对象相同大小的一段空间,还不能算是一个对象,因为构造函数没有执行
- A* p1 = (A*)malloc(sizeof(A));
- new(p1)A; // 注意:如果A类的构造函数有参数时,此处需要传参
- p1->~A();
- free(p1);
-
- A* p2 = (A*)operator new(sizeof(A));
- new(p2)A(10);
- p2->~A();
- operator delete(p2);
-
- return 0;
- }
6.malloc/free 与 new/delete 的区别
例:

注:概念性内容引自比特科技