Monday 23 April 2012

Deleting objects through pointer to void

An object of type T stored in dynamic memory (heap) can be safely deleted through pointer of type void* only if T is a POD type.

POD types are:

  • scalar types
  • POD classes
  • arrays of such types and
  • cv-qualified versions of these types

where

Scalar types are:

  • arithmetic(fundamental) types (like bool, char, int, float, double,...)
  • enumeration types
  • pointer types
  • pointer to member types
  • std::nullptr_t
  • cv-qualified versions of these types

Example 1: int is a POD type


Example 2: struct B is a POD type


Example 3: struct C is not a POD type

Memory leak is reported in debug output window when running Example 3:
Detected memory leaks!
Dumping objects ->
{144} normal block at 0x00595580, 4 bytes long.
Data: < > 01 00 00 00
Object dump complete.

This last example yields memory leak because delete applied to void* pointer freed memory allocated for C members but it did not call C destructor thus leaving memory pointed by p_ allocated.

No comments: