给定这样一个人为的示例结构:
static const int ARRAY_SIZE = 64;
struct some_struct
{
int buffer_size;
char buffer[ARRAY_SIZE] { 0 };
some_struct(char* str, int str_len) :
buffer_size(ARRAY_SIZE)
{
for (int i = 0; i < str_len; i++)
{
buffer[i] = str[i];
}
}
};
结构是否需要显式析构函数来释放数组的内存? 我打算在堆栈和堆上使用结构,即
// Stack
//
char myStr1[] = "string1";
some_struct myStackStruct(myStr1, 6);
...
// Heap
//
char myStr2[] = "string2";
some_struct* myHeapStruct = new some_struct(myStr2, 6);
...
delete myHeapStruct;
像这样的结构中固定大小的数组是否需要在析构函数中显式销毁?
最佳答案
Does the struct need an explicit destructor to free the array's memory? I intend to use the struct on the stack and the heap i.e.
您没有编写任何代码来在您的结构声明中从堆中指定任何内存分配。因此,数组声明不需要显式的 dtor 来释放内存。
Do fixed sized arrays in a struct like this need to be explicitly destroyed in a destructor?
一个简单的经验法则是 new
和 delete
成对出现。对于每个 new
,应该始终有一个 delete
。在您的结构声明中,您没有调用 new
,因此您不需要在 dtor 中显式销毁它。
然而,下一行将结构的一个实例放在堆上(因为您使用的是 new
)。因此,在这种情况下,您需要使用delete
来释放分配的内存。
some_struct* myHeapStruct = new some_struct(myStr2, 6);
关于c++ - 结构中固定大小的数组是否需要在 C++ 析构函数中显式销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47841547/