C++——内存管理

本文详细介绍了C++中的内存管理,包括C语言的malloc/calloc/realloc/free与C++的new/delete操作符。阐述了new和delete在处理内置类型与自定义类型时的不同,以及它们的实现原理。同时,文章还分析了不同变量在内存中的位置,并给出了相关的内存管理题目及解答。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++内存管理方式

C语言中动态内存管理方式:malloc/calloc/realloc/free
C语言内存管理方式在C++中可以继续使用,但有些地方就无能为力而且使用起来比较麻烦,因此C++又提出
了自己的内存管理方式:通过new和delete操作符进行动态内存管理。

new/delete操作内置类型:

void Test ()
{
 int* p1 = (int*) malloc(sizeof(int));
 free(p1);
 
 // 1.malloc/calloc/realloc的区别是什么?
 int* p2 = (int*)calloc(4, sizeof (int));
 int* p3 = (int*)realloc(p2, sizeof(int)*10);
 
 // 这里需要free(p2)吗?
 free(p3 );
}
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;
 }

申请和释放单个元素的空间,使用new和delete操作符,申请和释放连续的空间,使用new[]和delete[]

new和delete操作自定义类型:

class Test
{
public:
 Test()
 : _data(0)
 {
 cout<<"Test():"<<this<<endl;
 }
 ~Test()
 {
 cout<<"~Test():"<<this<<endl;
 }
 
private:
 int _data;
};
void Test2()
{
 // 申请单个Test类型的空间
 Test* p1 = (Test*)malloc(sizeof(Test));
 free(p1);
 
 // 申请10个Test类型的空间
 Test* p2 = (Test*)malloc(sizoef(Test) * 10);
 free(p2);
}

在申请自定义类型的空间时,new会调用构造函数,delete会调用析构函数,而malloc与free不会。

new和delete的实现原理

1.内置类型
如果申请的是内置类型的空间,new和malloc,delete和free基本类似,不同的地方是:new/delete申请和释放的是单个元素的空间,new[]和delete[]申请的是连续空间,而且new在申请空间失败时会抛异常,malloc会返回NULL。
2. 自定义类型
new的原理
1.调用operator new函数申请空间,
2.在申请的空间上执行构造函数,完成对象的构造
delete的原理
1.在空间上执行析构函数,完成对象中资源的清理工作
3. 调用operator delete函数释放对象的空间
new T[N]的原理
1.调用operator new[]函数,在operator new[]中实际调用operator new函数完成N个对象空间的申请
2. 在申请的空间上执行N次构造函数
delete[]的原理
1 在释放的对象空间上执行N次析构函数,完成N个对象中资源的清理
2. 调用operator delete[]释放空间,实际在operator delete[]中调用operator 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";
 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);
}
  1. 选择题:
    选项: A.栈 B.堆 C.数据段 D.代码段
    globalVar在哪里?____ staticGlobalVar在哪里?____
    staticVar在哪里?____ localVar在哪里?____
    num1 在哪里?____

char2在哪里?____ *char2在哪里?___
pChar3在哪里?____ *pChar3在哪里?____
ptr1在哪里?____ *ptr1在哪里?____
2. 填空题:
sizeof(num1) = ____;
sizeof(char2) = ____;
strlen(char2) = ____;
sizeof(pChar3) = ____;
strlen(pChar3) = ____;
sizeof(ptr1) = ____;
---------------
**globalVar在哪里?C staticGlobalVar在哪里?C
staticVar在哪里?C localVar在哪里?A
num1 在哪里?A
char2在哪里?A *char2在哪里?D
pChar3在哪里?A pChar3在哪里?D
ptr1在哪里?A ptr1在哪里?B
sizeof(num1) = 40;
sizeof(char2) = 5;
strlen(char2) = 4;
sizeof(pChar3) = 4;
strlen(pChar3) = 4;
sizeof(ptr1) = 4;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值