簡體   English   中英

C ++刪除包含新結構數組的新結構數組的正確方法?

[英]C++ Proper way of deleting a new struct array that contains new struct array?

刪除包含新結構數組的新結構數組的正確方法是什么?

typedef struct CALF_STRUCTURE
{
    char* Name;
    bool IsBullCalf;
} CALF;

typedef struct COW_STRUCTURE
{
    CALF* Calves;
} COW;

int main( void )
{
    COW* Cows;
    Cows = new COW[ 3 ];                // There are 3 cows.

    Cows[ 0 ].Calves = new CALF[ 2 ];   // The 1st cow has 2 calves.
    Cows[ 1 ].Calves = new CALF[ 1 ];   // The 2nd cow has only 1 calf.
    Cows[ 2 ].Calves = new CALF[ 25 ];  // The 3rd cow has 25 calves. Holy cow!

    Cows[ 2 ].Calves[ 0 ].Name = "Bob"; // The 3rd cow's 1st calf name is Bob.

    // Do more stuff...

現在,它的時間做清理! 但是......刪除牛和牛犢數組或任何類型的結構數組的正確方法是什么?

我應該首先在for循環中刪除所有牛的calves數組嗎? 像這樣:

// First, delete all calf struct array (cows[x].calves)
for( ::UINT CowIndex = 0; CowIndex != 3; CowIndex ++ )
    delete [ ] Cows[ CowIndex ].Calves;

// Lastly, delete the cow struct array (cows)
delete [ ] Cows;

return 0;
};

或者我應該只是刪除cows數組,並希望它也將刪除所有小牛數組? 像這樣:

// Done, lets clean-up
delete [ ] Cows;

return 0;
};

要么?

您必須手動刪除嵌套數組。

但是因為你正在使用C ++忘記數組而只使用std::vector

typedef struct COW_STRUCTURE
{
    std::vector<CALF> calves;
} COW;

int main( void ) {
  std::vector<COW> cows;

為什么不想使用能夠以高效且安全的方式為您管理一切的東西?

就像一個側面信息:

  • 類型名稱通常不是全部大寫(例如, Cowcow但很少COW ),大寫是常量
  • 變量通常是駝峰大小寫或帶下划線的小寫(所以calves不是Calves

都不是。 要在C ++中執行此操作:

struct CALF
{
    std::string Name;
    bool IsBullCalf;
};

struct COW
{
    std::vector<CALF> Calves;
};

並且,在main

std::vector<COW> Cows(3);

通過魔術,你不再需要刪除任何東西。

暫無
暫無

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

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