删除字符串数组

Deleting array of strings

本文关键字:数组 字符串 删除      更新时间:2023-10-16

假设我有一个字符串数组:

string* item

这个item数组是使用new运算符动态构造的。如果数组中的条目数numItems,如何释放此动态分配的内存?

使用new[]分配数组,delete[]释放数组:

#include <string>
std::string* item = new std::string[numItems];
...
delete[] item;

更好的选择是使用std::vector并让它为您处理内存:

#include <string>
#include <vector>
std::vector<std::string> item(numItems);