new和delete都叫表达式expression
operator new和operator delete
使用操作符new和delete动态分配和释放内存
使用new来分配新的内存块。
new的最常用的形式是返回一个指向请求内存的指针(成功),如果失败将会抛出异常。
在使用new时,需要指定为其分配内存的数据类型
Type* Pointer = new Type; // request memory for one element
// 为一个元素请求内存
为一个元素请求内存。
你还可以指定希望为其分配内存的元素数量(当需要为多个元素分配内存时)
Type* Pointer = new Type[numElements]; // request memory for numElements
为numelements请求内存。
因此,如果需要分配整数,可以使用以下语法:
int* pointToAnInt = new int; // get a pointer to an integer
int* pointToNums = new int[10]; // pointer to a block of 10 integers
上述2行代码分别是:
- 获取一个指向整数的指针
- 指向一个包含10个整数的块的指针
Note:
请注意,new表示对内存的请求。
不能保证分配调用总是成功,因为这取决于系统的状态和内存资源的可用性。
使用new的每个分配最终都需要通过delete使用相等和相反的反分配来释放:
Type* Pointer = new Type; // allocate memory 分配内存
delete Pointer; // release memory allocated above 释放上面分配的内存
此规则也适用于为多个元素请求内存时:
Type* Pointer = new Type[numElements]; // allocate a block 分配一个块
delete[] Pointer; // release block allocated above 释放上面分配的块
Note:
注意:delete[]的用法是当你用new[...]分配一个内存块的时候。
delete的用法是当你用new仅仅给一个元素分配内存的时候。
如果在停止使用分配的内存后没有释放它,那么该内存将保留并分配给你的应用程序。
这进而减少了应用程序可以使用的系统内存数量,甚至可能会降低应用程序的执行速度。(这被称为泄漏,应该不惜一切代价避免)
下面的代码演示了内存的动态分配和释放:
// LISTING 8.7 Accessing Memory Allocated Using new
// via Operator (*)
// and Releasing It Using delete
```c++
0: #include <iostream>
1: using namespace std;
2:
3: int main()
4: {
5: // Request for memory space for an int
5: // 为一个整数int请求内存空间
6: int* pointsToAnAge = new int;
7:
8: // Use the allocated memory to store a number
8: // 使用分配的内存来存储一个数字
9: cout << "Enter your dog’s age: ";
10: cin >> *pointsToAnAge;
11:
12: // use indirection operator* to access value
12: // 使用间接操作符来访问值
13: cout << "Age " << *pointsToAnAge << " is stored at 0x" << hex <<
pointsToAnAge << endl;
14:
15: delete pointsToAnAge; // release memory 释放内存
16:
17: return 0;
18: }
注意new返回一个指针,这就是它被赋值给一个指针的原因。
用户输入的年龄age使用cin和第10行中的dereference操作符(*)存储在这个新分配的内存中。
第13行再次使用dereference操作符(*)显示这个存储值,并显示存储该值的内存地址。
注意,第13行中的pointsToAnAge中包含的地址仍然是第6行中new返回的地址,并且此后没有更改。
注意:
操作符delete不能在指针中包含的任何地址上调用,而只能调用new返回的地址和delete尚未释放的地址。
因此,清单8.6中的指针包含有效地址,但是不应该使用delete来释放这些地址,因为对new的调用没有返回这些地址(就是因为没有new)。
请注意,当你使用new[...]分配一系列元素时,你将使用delete[]来解分配,如清单8.8所示。
// LISTING 8.8 Allocating Using new[…] and Releasing It Using
// delete[]
0: #include <iostream>
1: #include <string>
2: using namespace std;
3:
4: int main()
5: {
6: cout << "How many integers shall I reserve memory for?" << endl;
7: int numEntries = 0;
8: cin >> numEntries;
9:
10: int* myNumbers = new int[numEntries];
11:
12: cout << "Memory allocated at: 0x" << myNumbers << hex << endl;
13:
14: // de-allocate before exiting
15: delete[] myNumbers;
16:
17: return 0;
18: }
在执行期间,我们为5001个整数请求空间。在另一次运行中,它可能是20或55000。
元素数组的这种分配需要通过使用delete[]来释放内存来匹配。
操作符new和delete从空闲存储区中分配内存。
空闲存储是内存池形式的内存抽象,应用程序可以在其中分配(即保留)内存和释放(即释放)内存。