0
点赞
收藏
分享

微信扫一扫

c++内存管理

烟中雯城 2022-03-19 阅读 169

1.c++内存分布

首先是一段代码和相关问题。

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 在哪里? ____

c c c a a

char2 在哪里? ____ * char2 在哪里? ___

pChar3 在哪里? ____ * pChar3 在哪里? ____

ptr1 在哪里? ____ * ptr1 在哪里? ____

a a  a d a b

2.填空题

sizeof ( num1 ) = ____ ;

sizeof ( char2 ) = ____ ; strlen ( char2 ) = ____ ;

sizeof ( pChar3 ) = ____ ; strlen ( pChar3 ) = ____ ;

sizeof ( ptr1 ) = ____;

【说明】

1. 又叫堆栈,非静态局部变量 / 函数参数 / 返回值等等,栈是向下增长的。

2. 内存映射段 是高效的 I/O 映射方式,用于装载一个共享的动态内存库。用户可使用系统接口创建共享共 享内存,做进程间通信。(Linux 课程如果没学到这块,现在只需要了解一下)

3. 用于程序运行时动态内存分配,堆是可以上增长的。

4. 数据段 -- 存储全局数据和静态数据。

5. 代码段 -- 可执行的代码 / 只读常量。

2.c++语言中动态内存管理方式

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

2.1new/delete操作内置类型

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 Test
{
public:
	Test()
		: _data(0)
	{
		cout << "Test():" << this << endl;
	}
	~Test()
	{
		cout << "~Test():" << this << endl;
	}

private:
	int _data;
};
void Test2()
{
	// 申请单个Test类型的对象
	Test* p1 = new Test;
	delete p1;

	// 申请10个Test类型的对象
	Test* p2 = new Test[10];
	delete[] p2;
}
int main()
{
	Test2();
	return 0;
}class Test
{
public:
	Test()
		: _data(0)
	{
		cout << "Test():" << this << endl;
	}
	~Test()
	{
		cout << "~Test():" << this << endl;
	}

private:
	int _data;
};
void Test2()
{
	// 申请单个Test类型的对象
	Test* p1 = new Test;
	delete p1;

	// 申请10个Test类型的对象
	Test* p2 = new Test[10];
	delete[] p2;
}
int main()
{
	Test2();
	return 0;
}

上面这段代码中new申请的内存对象就会调用多少次构造函数和析构函数!

总结:new和malloc对于内置类型没有区别,只有用法上的区别!

3.operator new和operator delete函数

其实operator new和operator delete就是对malloc和free的封装

operator new中调用malloc申请内存,失败以后,改为抛异常处理错误,这样符合c++面向对象语言处理错误的方式。

new Stack

call operator new+call Stack构造函数

End.

举报

相关推荐

【c++】C/C++内存管理

【C++】C/C++内存管理

内存管理【C++】

C/C++内存管理

【C++】内存管理

C++内存管理

[C/C++]——内存管理

0 条评论