簡體   English   中英

C ++:釋放動態數組(結構的成員)和指向該結構的指針的方法

[英]C++: ways to free a dynamic array (member of a struct) and a pointer to this struct

所有。 假設我們有一個指向結構的指針,該結構的成員是動態數組(除其他成員外)。

我可以釋放所有對象,但希望您對這種特定情況的最佳實踐有自己的看法。 請參見下面的代碼,該代碼可以在沒有分段錯誤的情況下進行編譯和運行:

#include <iostream>

struct TestStruct
    {
    int a;  // And other members here
    int *b = new int[10];

    ~TestStruct()
        {
        }
    };

int main(void)
    {
    struct TestStruct *a_struct = new TestStruct();

    // Do something with the struct

    delete[] a_struct->b;
    delete a_struct;

    return 0;
    }

這樣,我假設內存已正確返回。 但是,如果我將所有這些刪除操作移至析構函數,則會出現段錯誤。 也就是說,如果我將數組刪除移動到析構函數( delete[] a_struct->b; ),它將不再可訪問,因為我之前刪除了指向該結構的指針( delete a_struct; ),反之亦然,並且delete a_struct;內存發生泄漏。

讀取此線程C ++釋放了struct占用的所有內存后 ,這並沒有定論,因為大多數建議都是理所當然的,但是其中很多存在段錯誤。

我簡化了問題,因為我將使用3D數組。 如果不可能釋放析構函數中100%的內存,那么我准備使用一種方法來運行循環以釋放數組內存和指向該結構的指針。 因此,我想知道您對這種特定情況的看法。

由於您使用的是C ++和動態數組,因此,與直接使用new相比, std::vectorstd::array或例如std::unique_ptr都是更好的處理方法。

正確的RAII方式是:

struct TestStruct
{
    int a;  // And other members here
    int *b = new int[10];

    ~TestStruct()
    {
            delete[] b;
    }
};

int main(void)
{
    struct TestStruct *a_struct = new TestStruct();

    delete a_struct;

    return 0;
}

正確的設計不允許同一指針字段多次刪除。 如果存在這種風險,則可以將nullptr分配給指針。 空指針的刪除是noop。

RAII(資源獲取是初始化)本質上可以歸結為:誰分配了內存,誰分配了內存。

在析構函數中,僅刪除動態分配的成員,而不刪除對象本身(這是在銷毀過程中完成的)。

因此,以下代碼應該可以:

struct TestStruct
{
  int a;  // And other members here
  int *b = new int[10];

  ~TestStruct() {
     delete[] b;
  }
};

int main(void)
{
  struct TestStruct *a_struct = new TestStruct();

  // Do something with the struct

  delete a_struct;

  return 0;

}

暫無
暫無

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

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