原文: https://www.programiz.com/cpp-programming/memory-management
数组可用于存储多个同类数据,但是使用数组存在严重缺陷。
声明数组时应分配内存,但在大多数情况下,直到运行时才能确定所需的确切内存。
在这种情况下,最好的做法是声明一个具有最大可能所需内存的数组(声明一个预期具有最大可能大小的数组)。
不利的一面是未使用的内存被浪费了,不能被任何其他程序使用。
为了避免浪费内存,您可以在 C++ 中使用new和delete运算符动态分配运行时所需的内存。
C++ 程序,用于存储n个学生的 GPA,并显示在其中n是用户输入的学生人数。
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;
// memory allocation of num number of floats
ptr = new float[num];
cout << "Enter GPA of students." << endl;
for (int i = 0; i < num; ++i)
{
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}
cout << "\nDisplaying GPA of students." << endl;
for (int i = 0; i < num; ++i) {
cout << "Student" << i + 1 << " :" << *(ptr + i) << endl;
}
// ptr memory is released
delete [] ptr;
return 0;
} 输出
Enter total number of students: 4
Enter GPA of students.
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9
Displaying GPA of students.
Student1 :3.6
Student2 :3.1
Student3 :3.9
Student4 :2.9 在此程序中,仅动态声明存储num(由用户输入)数量的浮点数据所需的内存。
ptr = new float[num];上面程序中的此表达式将指针返回到刚好足以容纳num个浮点数据的内存部分。
使用new运算符分配内存后,应将其释放回操作系统。
如果程序使用new占用大量内存,则系统可能会崩溃,因为操作系统没有可用的内存。
以下表达式将内存返回给操作系统。
delete [] ptr;方括号[]表示数组已删除。 如果您需要删除单个对象,则无需使用方括号。
delete ptr;面向对象的方法来处理 C++ 中的上述程序。
#include <iostream>
using namespace std;
class Test
{
private:
int num;
float *ptr;
public:
Test()
{
cout << "Enter total number of students: ";
cin >> num;
ptr = new float[num];
cout << "Enter GPA of students." << endl;
for (int i = 0; i < num; ++i)
{
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}
}
~Test() {
delete[] ptr;
}
void Display() {
cout << "\nDisplaying GPA of students." << endl;
for (int i = 0; i < num; ++i) {
cout << "Student" << i+1 << " :" << *(ptr + i) << endl;
}
}
};
int main() {
Test s;
s.Display();
return 0;
} 该程序的输出与上述程序相同。
创建对象Test时,将调用构造器,该构造器为num浮点数据分配内存。
当对象被销毁时,即,对象超出范围时,将自动调用析构器。
~Test() {
delete[] ptr;
}
该析构器执行delete[] ptr;,并将内存返回给操作系统。