C++ 中的内存管理是一种控制计算机内存并为程序执行分配必要内存量的方法。由于它与其他编程语言共享相同的基本思想,因此几乎可以理解。它通过对整体计算机系统功能的改进来处理空间和内存的分配。在内存管理中使用数组至关重要,因为它们能够以合适的间距对齐方式存储数据,维护时间约束,并通过使用 new 关键字进行内存分配来有效管理资源。
C 语言中的 malloc() 和 calloc() 函数用于在运行时动态分配内存,free() 函数用于释放动态分配的内存。C++ 包含这些函数,以及 new 和 delete 这两个运算符,它们改进并简化了内存的分配和释放操作。使用 new 和 delete 运算符,我们可以动态分配和随后释放内存。
语法
pointer_variable = new data-type;
new 运算符使用上述语法创建对象。在上述语法中,指针变量的名称是“pointer variable”,"new" 是运算符,"data-type" 指定数据类型。
例如,让我们理解下面的代码
// an int pointer declaration
int* ptVar;
// memory is allocated dynamically
// the new keyword is used
ptVar = new int;
// assign value to allocated memory
*pttVar = 7;
在这里,我们使用 new 运算符为 int 变量动态分配内存。
您会看到我们通过使用指针 ptVar 动态分配了内存。这是因为 new 运算符返回内存位置的地址。
对于数组,new 运算符返回数组第一个元素的地址。
由于程序员有责任释放动态分配的内存,C++ 语言提供了 delete 运算符。
如果我们不再需要动态声明的变量,我们可以释放它所使用的内存。
delete 运算符用于此目的。在此过程中,操作系统收回内存。这被称为内存释放。
语法
delete ptr_var;
例如,让我们理解下面的代码
// int pointer declaration
int* ptVar;
// dynamically allocate the memory for an int variable
ptVar = new int;
// value is assigned to the variable memory
*ptVar = 9;
// print the value which is stored in memory
cout << *ptVar; // Output: 9
// deallocate the memory
delete ptVar;
#include <iostream>
using namespace std;
int main() {
// int pointer is declared
int* pInt;
// float pointer is declared
float* pFloat;
// allocate the memory dynamically
pInt = new int;
pFloat = new float;
// assigning value to the memory
*pInt = 2f;
*pFloat = 2.24f;
cout << *pInt << endl;
cout << *pFloat << endl;
// deallocate the memory
delete pInt, pFloat;
return 0;
}
输出
2 2.24
在这个程序中,我们使用动态内存分配创建了两个 int 和 float 类型的变量。我们给它们赋值,打印它们,然后释放删除的内存。