在 C++ 中使用 delete 运算符
    
    Jinku Hu
    2023年10月12日
    
    C++
    C++ Memory
    
 
本文将说明在 C++ 中如何使用 delete 运算符的几种方法。
使用 delete 运算符释放对象的已分配资源
    
使用 new 运算符动态分配的对象应在程序退出之前释放,这意味着调用方负责显式调用 delete 操作。请注意,可以使用构造函数初始化程序使用 new 运算符声明和初始化对象。下面的示例代码演示了这种情况,然后在从 main 函数返回之前释放相应的资源。注意不要在堆对象上调用 delete 运算符会导致内存泄漏,从而导致长时间运行的进程占用大量内存。
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
using std::cout;
using std::endl;
using std::setw;
using std::string;
using std::vector;
int main() {
  int *num = new int(1024);
  auto *sp = new string(10, 'a');
  cout << *num << endl;
  cout << *sp << endl;
  for (const auto &item : *vp) {
    cout << item << ", ";
  }
  cout << endl;
  delete num;
  delete sp;
  return EXIT_SUCCESS;
}
输出:
1024
aaaaaaaaaa
new 和 delete 运算符也可以与标准库容器一起使用。即,在以下示例代码中的单个语句中分配和初始化了 std::vector 对象。一旦 new 运算符返回指向 vector 的指针,我们就可以像常规的 vector 对象一样对其进行操作。
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
using std::cout;
using std::endl;
using std::setw;
using std::vector;
int main() {
  auto *vp = new vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  for (const auto &item : *vp) {
    cout << item << ", ";
  }
  cout << endl;
  delete vp;
  return EXIT_SUCCESS;
}
输出:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
使用 delete 运算符释放向量中的元素
将 delete 运算符与动态分配的数组一起使用会略有不同。通常,new 和 delete 一次对一个对象进行操作,但是数组需要通过一次调用分配多个元素。因此,方括号表示法用于指定数组中元素的数量,如以下示例代码所示。这样的分配返回指向第一个元素的指针,可以将其取消引用以访问不同的成员。最后,当不需要数组时,应使用特殊的删除符号将其释放,该符号包含空方括号,以确保每个元素都已被释放。
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>
using std::cout;
using std::endl;
using std::setw;
using std::vector;
constexpr int SIZE = 10;
constexpr int MIN = 1;
constexpr int MAX = 1000;
void initPrintIntVector(int *arr, const int &size) {
  std::random_device rd;
  std::default_random_engine eng(rd());
  std::uniform_int_distribution<int> distr(MIN, MAX);
  for (int i = 0; i < size; ++i) {
    arr[i] = distr(eng) % MAX;
    cout << setw(3) << arr[i] << "; ";
  }
  cout << endl;
}
int main() {
  int *arr1 = new int[SIZE];
  initPrintIntVector(arr1, SIZE);
  delete[] arr1;
  return EXIT_SUCCESS;
}
输出:
311; 468; 678; 688; 468; 214; 487; 619; 464; 734;
266; 320; 571; 231; 195; 873; 645; 981; 261; 243;
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Jinku Hu
    
