c++ - 结构中固定大小的数组是否需要在 C++ 析构函数中显式销毁?

标签 c++ arrays struct

给定这样一个人为的示例结构:

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?

一个简单的经验法则是 newdelete 成对出现。对于每个 new,应该始终有一个 delete。在您的结构声明中,您没有调用 new,因此您不需要在 dtor 中显式销毁它。

然而,下一行将结构的一个实例放在堆上(因为您使用的是 new)。因此,在这种情况下,您需要使用delete 来释放分配的内存。

some_struct* myHeapStruct = new some_struct(myStr2, 6);

关于c++ - 结构中固定大小的数组是否需要在 C++ 析构函数中显式销毁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47841547/

相关文章:

c++ - boost 智能指针对我有帮助吗?

c++ - 冒泡排序算法不起作用

java - 大字节数组使用的堆比预期多

异常情况下的 C++ 错误 C2228( '.val' 左侧必须有类/结构/union )

c++ - 正在发送 UDP 广播,但未收到

c++ - 为什么 GCC 不报告未初始化的变量?

Java:对象中的数组属性

arrays - 如何判断 append 是否创建了一个新的底层数组

swift - 如何创建结构并附加到其中的数组?

c++ - 在 C++ 中,将 int 拆分为位的正确术语是什么