所有。 假设我们有一个指向结构的指针,该结构具有一个动态数组成员(以及其他成员)。
我可以释放所有对象,但希望您对这种特定情况的最佳实践有所了解。请参阅下面的代码,它编译并运行时没有分段错误:
#include <iostream>
struct TestStruct
{
int a; // And other members here
int *b = new int[10];
~TestStruct()
{
}
};
int main(void)
{
struct TestStruct *a_struct = new TestStruct();
// Do something with the struct
delete[] a_struct->b;
delete a_struct;
return 0;
}
这样我假设内存正确返回。但是,如果我将任何这些删除移动到析构函数,则会出现段错误。也就是说,如果我将数组删除移动到析构函数(delete[] a_struct->b;
),则它不再可访问,因为我在(delete a_struct;
)之前删除了指向结构的指针,反之亦然,并且内存泄漏发生的情况。
在阅读了这个帖子C++ free all memory used by struct后,它有点不确定,因为大多数建议被认为是理所当然的,但其中很多都存在段错误。
我已经简化了问题,因为我将使用的数组是3D。如果不可能在析构函数中释放100%的内存,那么我准备使用一个方法来运行循环以释放数组内存和指向结构的指针。所以我想知道你对这种特殊情况的看法。
答案 0 :(得分:3)
由于您使用的是C ++和动态数组,std::vector
,std::array
或者例如std::unique_ptr
都是比直接使用new
更好的处理方法。
答案 1 :(得分:0)
适当的RAII方式是:
struct TestStruct
{
int a; // And other members here
int *b = new int[10];
~TestStruct()
{
delete[] b;
}
};
int main(void)
{
struct TestStruct *a_struct = new TestStruct();
delete a_struct;
return 0;
}
正确的设计不允许通过相同的指针进行多次删除。如果存在此类风险,您可以将nullptr
指定给指针。删除空指针是noop。
答案 2 :(得分:0)
在析构函数中,只删除动态分配的成员,而不删除对象本身(这在破坏过程中完成)。
所以下面的代码应该没问题:
struct TestStruct
{
int a; // And other members here
int *b = new int[10];
~TestStruct() {
delete[] b;
}
};
int main(void)
{
struct TestStruct *a_struct = new TestStruct();
// Do something with the struct
delete a_struct;
return 0;
}