分配和释放内存(,) [英] Allocating and freeing memory (, )
问题描述
大家好,
假设我有一个结构数组,其大小是动态确定的:
Hello all,
Let''s assume that I have an array of structures, where the size is determined dynamically:
myStruct *pMyStruct = new myStruct[structSize];
并假设myStruct具有一个成员,该成员是指向字符串数组的指针:
and let''s assume that myStruct has a member which is a pointer to an array of strings:
string *pMyList;
我在代码中的某个地方分配了一个字符串临时数组:
Somewhere in the code I allocate a temporary array of strings:
string *pTempList = new string[listSize];
然后在代码中,我将该临时数组分配给myStruct的实例
and later in the code I assign that temporary array to the instances of myStruct
pMyStruct[i].pMyList = pTempList;
问题是一旦完成myStruct实例,我应该如何释放内存.
我是否需要在[structSize]上循环,以便为myStruct的每个实例释放pMylist,然后释放pMyStruct(然后释放pTempList)?
最好的问候,
Enrique
The question is how I should free the memory once I am done with the instances of myStruct.
Do I have to make a loop over [structSize] where I free pMylist for every instance of myStruct, then free pMyStruct (and then free pTempList)?
Best regards,
Enrique
推荐答案
Enrique,
您对std::string
的询问不同,因为您知道它们具有自己的内部内存管理.
同样,标准C ++库为std::vector<>
提供内部内存管理.
如果使用它而不是C数组,则您的问题将如下所示:
..假设myStruct具有一个成员,该成员是字符串数组的指针字符串向量:
Hi Enrique,
You don''t have the same interrogation about yourstd::string
s because you know that they have their own internal memory management.
Similarly the Standard C++ Library providesstd::vector<>
with internal memory management.
If you used it instead of C arrays your question would look like:
.. let''s assume that myStruct has a member which isa pointer to an array of stringsa vector of strings:
struct myStruct
{
std::vector<std::string> MyList;
};
让我们假设我有一个一个数组一个结构的矢量,其大小是动态确定的:
Let''s assume that I have an array a vector of structures, where the size is determined dynamically:
std::vector<myStruct> MyStruct(structSize);
在代码中的某个地方,我分配了一个临时的 array 字符串向量:
Somewhere in the code I allocate a temporary array vector of strings:
std::vector<std::string> TempList(listSize);
,随后在代码中,我将该临时 array 向量分配给myStruct实例
and later in the code I assign that temporary array vector to the instances of myStruct
MyStruct[i].MyList = TempList;
问题是,一旦完成myStruct实例,我应该如何释放内存.
答案将是:您无需执行任何操作,所有内存都被释放在对象析构函数中,当它们超出范围时将被调用.
欢呼声,
AR
The question is how I should free the memory once I am done with the instances of myStruct.
The answer would be: You have nothing to do, all memory is deallocated in the objects destructors which are called when they get out of scope.
cheers,
AR
这篇关于分配和释放内存(,)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!