Reputation: 542
What is the 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...
Now, its time do clean-up! But...what is the proper way of deleting the cows and calves array or any type of struct array?
Should I delete all of the cows's calves array in a for-loop first? Like this:
// 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;
};
Or should I just simply delete the cows array and hope that it will also delete all calves array? Like this:
// Done, lets clean-up
delete [ ] Cows;
return 0;
};
Or?
Upvotes: 0
Views: 306
Reputation: 258558
Neither. To do this in C++:
struct CALF
{
std::string Name;
bool IsBullCalf;
};
and
struct COW
{
std::vector<CALF> Calves;
};
and, in main
:
std::vector<COW> Cows(3);
By magic, you no longer need to delete anything.
Upvotes: 1
Reputation: 133567
You will have to manually delete nested arrays.
But since you are using C++ forget about arrays and just use std::vector
:
typedef struct COW_STRUCTURE
{
std::vector<CALF> calves;
} COW;
int main( void ) {
std::vector<COW> cows;
Why don't you want to use something that will manage everything for you in an efficient and moreover safe way?
Just as a side info:
Cow
or cow
but rarely COW
), capitalization is for constantscalves
not Calves
)Upvotes: 1