C++ 使用 delete[] 删除结构数组
C++ Deleting array of structures with delete[]
我在向 cpp 中的数组添加结构时遇到问题。我想出了这种方法,它对整数很有效,但是当我想对结构做同样的事情时,我在添加 3 个或更多后出现错误。我稍微调试了一下,似乎 delete[] 导致错误消息“Segmentation fault (core dumped)”。我不能使用来自 stl 的矢量或列表,所以不要建议这是一些代码:
struct sth
{
unsigned int id;
std::string name;
};
unsigned int id_counter = 0;
unsigned int counter_int = 0;
sth *array = new sth[0];
void print_array()
{
for (int i = 0; i < counter_int; ++i)
{
std::cout << array[i].id << ' ' << array[i].name << " -- ";
}
std::cout << '\n';
}
void add_sth(sth value)
{
sth *newArr = new sth[counter_int + 1];
memcpy(newArr, array, counter_int * sizeof(sth));
delete[] array;
array = newArr;
array[counter_int] = value;
++id_counter;
++counter_int;
}
int main(int argc, char const *argv[])
{
sth e1 = {1, "abc1"};
sth e2 = {2, "abc2"};
add_sth(e1);
add_sth(e2);
add_sth(e2);
print_array();
}
问题可能是试图用 memcpy 复制 std::string
。
std::string
不是 POD(普通旧数据)对象,一些编译器和
当然是静态代码分析器,例如SonarQube 或 Klocwork 会提醒你
你的做法是错误的。
要正确完成复制,您应该定义一个赋值运算符,并且
一个一个地复制项目,或者只使用动态容器,例如std::vector
sth
结构有一个 std::string
成员,因此使用 memcpy
将无法正常工作,因为 sth
不是 trivially-copyable。 memcpy
函数对包含 non-POD 成员的 C++ 或 C++ 类 一无所知。
在 C++ 中,您可以将 memcpy
替换为 std::copy:
#include <algorithm>
//...
std::copy(array, array + counter_int, newArr);
一个好的 C++ 编译器会在检测到类型为 trivially-copyable 时将 std::copy
转换为 memcpy
。否则编译器将简单地使用循环复制对象。
我在向 cpp 中的数组添加结构时遇到问题。我想出了这种方法,它对整数很有效,但是当我想对结构做同样的事情时,我在添加 3 个或更多后出现错误。我稍微调试了一下,似乎 delete[] 导致错误消息“Segmentation fault (core dumped)”。我不能使用来自 stl 的矢量或列表,所以不要建议这是一些代码:
struct sth
{
unsigned int id;
std::string name;
};
unsigned int id_counter = 0;
unsigned int counter_int = 0;
sth *array = new sth[0];
void print_array()
{
for (int i = 0; i < counter_int; ++i)
{
std::cout << array[i].id << ' ' << array[i].name << " -- ";
}
std::cout << '\n';
}
void add_sth(sth value)
{
sth *newArr = new sth[counter_int + 1];
memcpy(newArr, array, counter_int * sizeof(sth));
delete[] array;
array = newArr;
array[counter_int] = value;
++id_counter;
++counter_int;
}
int main(int argc, char const *argv[])
{
sth e1 = {1, "abc1"};
sth e2 = {2, "abc2"};
add_sth(e1);
add_sth(e2);
add_sth(e2);
print_array();
}
问题可能是试图用 memcpy 复制 std::string
。
std::string
不是 POD(普通旧数据)对象,一些编译器和
当然是静态代码分析器,例如SonarQube 或 Klocwork 会提醒你
你的做法是错误的。
要正确完成复制,您应该定义一个赋值运算符,并且
一个一个地复制项目,或者只使用动态容器,例如std::vector
sth
结构有一个 std::string
成员,因此使用 memcpy
将无法正常工作,因为 sth
不是 trivially-copyable。 memcpy
函数对包含 non-POD 成员的 C++ 或 C++ 类 一无所知。
在 C++ 中,您可以将 memcpy
替换为 std::copy:
#include <algorithm>
//...
std::copy(array, array + counter_int, newArr);
一个好的 C++ 编译器会在检测到类型为 trivially-copyable 时将 std::copy
转换为 memcpy
。否则编译器将简单地使用循环复制对象。