Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 结构中的固定大小数组是否需要在C+中显式销毁+;析构函数?_C++_Arrays_Struct - Fatal编程技术网

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

C++ 结构中的固定大小数组是否需要在C+中显式销毁+;析构函数?,c++,arrays,struct,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;

给出这样一个精心设计的示例结构:

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];
        }
    }
};
像这样的结构中的固定大小数组是否需要在析构函数中显式销毁

结构是否需要显式析构函数来释放数组的 记忆?我打算在堆栈和堆上使用struct,即


您没有在结构声明中编写任何指定堆内存分配的代码。因此,数组声明不需要显式dtor来释放内存

像这样的结构中的固定大小数组是否需要显式 在析构函数中被摧毁

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

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

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

不需要,不需要显式销毁固定大小的数组成员

数组是结构数据的一部分,因此在销毁结构时它将被销毁

您可以使用
sizeof()
看到这一点:


一般来说,每一次破坏都与一次创造相匹配;只有显式创建了某个对象,才能显式销毁它。如果在堆栈上声明一个
some_-struct
实例,当
some_-struct
超出范围时,数据将被卸载。如果使用
new()
malloc()
分配
some_结构
,则数据将位于单个块中,在
delete()
free()时卸载
some_struct实例。

如果类内部使用
new
,则必须定义析构函数以适当地使用
delete
:此外,如果定义类的析构函数,还应定义类的复制构造函数和重载
运算符=()
参考3、4或5的规则

如果您的类没有在内部使用
new
,则不会


如果在其他代码段中对类本身使用new,则必须在需要时删除该类

不需要。仅
delete
您所需的
new
。您也不需要在构造函数的成员初始值设定项列表中提及它。使用std::string,而不是char数组。另一个经验法则是,您只能删除指针。数组不是指针。“您没有编写任何代码来指定堆中的任何内存分配。”这不是堆内存吗?some_struct*myHeapStruct=新的some_struct(myStr2,6)@ChrisMcJava:这是来自堆的分配。然而,我指的是你的struct声明,我编辑了我的答案来澄清这一点。
some_struct* myHeapStruct = new some_struct(myStr2, 6);
struct some_struct
{
    char[64] data;
};

static_assert(sizeof(some_struct) == 64 * sizeof(char));