我有这些场景,我想知道是否正确管理我的内存。我在启动可执行文件时观察任务管理器中的内存消耗情况,并查看内存未如何回弹到初始量,这导致我怀疑内存不在需要的位置。 因此,在第一种情况下我有一个功能,增加了一个新的元素,以一个动态数组:所以在C++中使用指针时的内存管理
struct Color {
int R;
int G;
int B;
}
int TotalColors;
Color* Rainbow;
void AddColor(Color NewColor) {
// So, I create a new array of size TotalColors+1
Color* NewRainbow = new Color[TotalColors+1];
// Now I add the existing elements
for (int i=0; i<TotalColors; i++) {
NewRainbow[i] = Rainbow[i];
}
// And lastly, I add the new element
NewRainbow[TotalColors] = NewColor;
// Now, I assign the NewRainbow to Rainbow (I don't know if it's correct)
Rainbow = NewRainbow;
}
,在这种情况下,你觉得我错过了什么?这是工作,但我想确保未使用的东西从内存中删除。 我也有一个功能来删除一个元素,它看起来像这样:
void RemoveColor(Color Removable) {
// Again, I create a new array of size TotalColors-1
Color* NewRainbow = new Color[TotalColors-1];
// I scan the list and add only those elements which are not 'Removable'
for (int i=0; i<TotalColors; i++) {
// Let's suppose that Removable exists in the list
if (Rainbow[i].R != Removable.R && Raibow[i].G != Removable.G && ... {
NewRainbow [i] = Rainbow[i];
}
}
// Again, the same operation as above
NewRainbow[TotalColors] = NewColor;
Rainbow = NewRainbow;
}
在这种情况下,我不知道有彩虹[移动]发生什么,我的意思是,数组的元素是除去。 最后一种情况是,我尝试从数组中发送一个元素的指针到一个函数。
Color* GetColor(int Index) {
Color* FoundColor;
// Scan the array
for (int i=0; i<TotalColors; i++) {
if (i == Index) FoundColor = &Rainbow[i];
}
return FoundColor;
}
// And I use it like this
void ChangeColor(int Index) {
Color* Changeable;
Changeable = GetColor(Index);
SetRGB(Changeable, 100, 100, 100);
}
// And this is what changes the value
void SetRGB(Color* OldRGB, int R, int G, int B) {
(*oldRGB).R = R;
(*oldRGB).G = G;
(*oldRGB).B = B;
}
就是这样。所以,这有效,但我不确定是否有这么多的指针,我没有忘记删除一些东西。例如,当我RemoveColor
我看不到内存改变(也许有些字节没有改变),我只是想要一些专业的眼睛告诉我,如果我错过了什么。谢谢!
管理原始指针确实很棘手。有没有理由不使用智能指针? –
只是学习。我也可以使用矢量。谢谢 – ali