Rella
Rella

Reputation: 66965

Is it possible to delete C POD using delete in C++?

Having structs like

struct ifoo_version_42 {
   int x, y, z;
   char *imageData;
};

where imageData is something like imageData = new char[50000];

Can we perform something like:

template< typename T >
void del( T a ) // we promise to use this only on C Plain Old data structs=)
{
  delete a;
}

on this structure an will it be enough to clean memory form if?

Upvotes: 3

Views: 405

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279335

Deleting the struct does not recursively delete any pointers in it, and hence doesn't free the array of char pointed to by imageData.

I'm also a bit confused by your use of delete[]. You can free an array (allocated with new[]) using delete[], or free a single object (allocated with new) using delete. You can't mix them, and you don't say how you're allocating one or more instances of ifoo_version_42. For example the following has undefined behavior:

ifoo_version_42 *x = new ifoo_version_42;
del(x);

The following is OK:

ifoo_version_42 *x = new ifoo_version_42[1];
del(x);

Upvotes: 5

If you perform your del function on an ifoo_version_42, then the memory block pointed to by data will not be freed; neither delete nor delete[] work recursively.

delete[] is meant to be used for freeing arrays; that is, if you allocated imageData with new[], then it should be freed with delete[].

delete is meant to be used for freeing single objects: If you e.g. allocated a ifoo_version_42 with new, then you should free it with delete.

(Also, never use delete for something allocated with malloc(), or free() with something allocated with new.)

One further suggestion: Learn the RAII idiom and use smart pointer classes provided by the STL or Boost libraries; these go a long way towards helping you with correct memory management.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

This function template would also "work" on non-POD types. It's literally no different from invoking delete[] a; directly.

However, this won't delete the memory associated with imageData. That's typically the sort of thing you do in a destructor.

Upvotes: 5

Related Questions