簡體   English   中英

在C ++中使用指針時的內存管理

[英]Memory management when working with pointers in 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;
}

在這種情況下,我不知道Rainbow [Removable]會發生什么,我的意思是刪除了數組的元素。 最后一種情況是,我嘗試將元素的指針從數組發送到函數。

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時,我看不到內存發生了變化(也許有些字節沒有影響),我只是想讓專業的眼睛告訴我是否錯過了某些事情。 謝謝!

在第一個函數AddColor()您不會刪除先前分配的內存。

Rainbow = NewRainbow; // leaking the memory Rainbow was previously pointing to.

將最后一行更改為:

delete[] Rainbow;
Rainbow = NewRainbow;

RemoveColor()相同

每當您使用new運算符時,都需要進行相應的delete 另外,如果您要分配帶有new[]的數組,則必須具有相應的delete[]

為了不擔心您是否忘記刪除指針,不應使用普通指針。 相反,請使用智能指針,例如

std::shared_ptr
std::unique_ptr
etc.

或者,如果您還沒有C ++ 11,請使用

boost::shared_ptr
boost::scoped_ptr

有關智能指針的更多信息,請參見Wikipedia和特定文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM