C++的内存管理,相对于高级语言Java、C#等有自己的GC回收机制而言,C++是需要程序员更主动来管理内存。查资料说C++的内存管理,有很多种:手动、RAII释放、scope_guard/defer释放技术、Boehm GC库等。一个好的C++资源管理策略,对您的游戏性能影响是非常大的。
本篇主要介绍手动分配与释放内存案例。new与delete运算符地运用。
/*
* Author:W;
* 内存手动管理
* 1.内存分配:new 运算符,为给定类型的变量在运行时分配堆内的内存,并返回所分配的空间地址。
* 2.内存回收:delete 运算符。当不再需要动态分配的内存空间时。
*/
//引入标准输入输出流
#include <iostream>
using namespace std;
/*箱子*/
class Box
{
public:
Box();
~Box();
private:
int id;
};
Box::Box()
{
cout << "创建Box实例:" << endl;
}
Box::~Box()
{
cout << "销毁Box实例" << endl;
}
//main程序执行入口函数
int main()
{
cout << "===1.基本数据类型的内存分配与回收===" << endl;
//1.基本数据类型的内存分配与回收
int* num = NULL;
num = new int;//手动分配内存
*num = 5;
cout << "num = " << *num << endl;
delete num;//手动释放内存
cout << "===2.数组的内存分配与回收===" << endl;
//2.数组的内存分配
/*====一维数组====*/
cout << "一维数组内存分配与回收" << endl;
int* arr1 = new int[5];//手动申请数组内存
for (int i = 0; i < 5; i++)
{
arr1[i] = i + 1;
}
for (int i = 0; i < 5; i++)
{
cout << "arr1[" << i << "] = " << arr1[i] << endl;
}
//手动释放数组内存
delete [] arr1;
cout << "二维数组内存分配与回收" << endl;
/*====二维数组====*/
int** arr2 = NULL;
//手动申请二维数组内存
int x = 2;
int y = 3;
arr2 = new int*[x];
for (int i = 0; i < x; i++)
{
arr2[i] = new int[y];
}
//赋值
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
arr2[i][j] = j * i;
}
}
//打印
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
cout << "arr2[" << i << "][" << j << "] = " << arr2[i][j] << endl;
}
}
//手动释放二维数组的内存
for (int i = 0; i < x; i++)
{
delete [] arr2[i];
}
delete [] arr2;
cout << "三维数组内存分配与回收" << endl;
/*====三维数组====*/
int*** arr3 = NULL;
int a = 2;
int b = 2;
int c = 2;
//手动分配内存
arr3 = new int** [a];
for (int i = 0; i < a; i++)
{
arr3[i] = new int* [b];
for (int j = 0; j < b; j++)
{
arr3[i][j] = new int[c];
}
}
//赋值
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
for (int k = 0; k < c; k++)
{
arr3[i][j][k] = i + j + k;
}
}
}
//打印
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
for (int k = 0; k < c; k++)
{
cout << "arr3[" << i << "][" << j << "][" << k << "] = " << arr3[i][j][k] << endl;
}
}
}
//手动释放内存
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
delete[] arr3[i][j];
}
}
for (int i = 0; i < a; i++)
{
delete [] arr3[i];
}
delete[] arr3;
cout << "===3.对象的内存分配与回收===" << endl;
//3.对象的内存分配与回收
Box* boxArr = new Box[3];
//对象数组内存释放
delete [] boxArr;
}
运行结果如下:
?
|