Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to delete a structure?

Tags:

Structure I created:

   struct VideoSample   {        const unsigned char * buffer;       int len;   };     VideoSample * newVideoSample = new VideoSample;    newVideoSample->buffer = buf;    newVideoSample->len = size;         //... 

How now to delete it now?

like image 433
Rella Avatar asked Nov 09 '10 13:11

Rella


People also ask

How do you delete a struct?

The best way to explicitly remove a Struct is to assign an empty value to the struct variable that refers to a Struct. Example: Assign a new value to the Struct variable that refers to the Struct.

How do you delete a data structure in C++?

delete keyword in C++ Which means Delete operator deallocates memory from heap. Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.

How do you delete a struct array?

Overall, the combination allows deleting the array of structs using delete[] .

Do you have to delete structs?

if a struct is created as a variable in a scope, it is automatically deleted at the end the the scope. And if you are creating it with "new", why don't you use "delete" to free it ?


2 Answers

delete newVideSample; 

This won't free any memory you allocated to newVideoSample->buffer though - you have to free it explicitly before deleting.

//Free newVideSample->buffer if it was allocated using malloc free((void*)(newVideSample->buffer));  //if it was created with new, use `delete` to free it delete newVideSample->buffer;  //Now you can safely delete without leaking any memory delete newVideSample; 

Normally this kind of freeing is written in the destructor of the class so that it'll be called automatically when you delete the dynamically created object.

Thanks @steve for mentioning it :)

like image 184
Amarghosh Avatar answered Jan 15 '23 01:01

Amarghosh


delete newVideoSample; 

But if the new and delete are in the same context, you're probably better off skipping them and just creating it on the stack instead:

VideoSample newVideoSample = {buf, size}; 

In that case, no cleanup is necessary.

like image 26
aschepler Avatar answered Jan 15 '23 02:01

aschepler