matthias_buehlmann
matthias_buehlmann

Reputation: 5091

c++ propper overriding of new[] and delete[]

In this library there are the following global overrides for new, delete, new[] and delete[]:

/* ------------------------------------------------------------ */
/* ---------------------- new and delete ---------------------- */
/* ------------------------------------------------------------ */

/* ---------------------------------------- operator new */

void *operator new(size_t size)
{
    void *p = MemTrack::TrackMalloc(size);
    if (p == NULL) throw std::bad_alloc();
    return p;
}

/* ---------------------------------------- operator delete */

void operator delete(void *p)
{
    MemTrack::TrackFree(p);
}

/* ---------------------------------------- operator new[] */

void *operator new[](size_t size)
{
    void *p = MemTrack::TrackMalloc(size);
    if (p == NULL) throw std::bad_alloc();
    return p;
}

/* ---------------------------------------- operator delete[] */

void operator delete[](void *p)
{
    MemTrack::TrackFree(p);
}

The overrides for new and delete make sense to me. But what about new[] and delete[]? AFAIK in c++ when a new array is created using new[], it also stores the number of elements before the pointer, so that delete[] can call the destructors on the elements. Does this need to be considered when overriding new[] and delete[] or is there some kind of implicit "wrapper" that adds that on the outside of whatever the overriding implementation allocates? If not, how is it done properly? it seems the new[] operator also only gets the number of bytes that should be allocated, and not the number of elements.

Upvotes: 2

Views: 68

Answers (2)

Victor
Victor

Reputation: 470

According to CPP reference, the standard library implementation of new[] actually calls new:

  1. Called by the array form of new[]-expressions to allocate all storage required for an array (including possible new-expression overhead). The standard library implementation calls version (1)

Makes sense, because in both cases the parameter size of the operator new indicates the number of bytes to be allocated, neglecting the number of objects, which is irrelevant to this operator. The operator that cares about the number of objects is operator [].

Upvotes: 0

john
john

Reputation: 88092

Your assumption is wrong

AFAIK in c++ when a new array is created using new[], it also stores the number of elements

Nothing in C++ says how new[] must be implemented.

Note new and new[] are not the same as operator new and operator new[], The former call constructors (and maybe in the case of new[] do some bookkeeping to track how many elements are constructed, I guess this is the wrapper you mentioned). The only responsibility of operator new and operator new[] is to allocate sufficient memory.

Upvotes: 1

Related Questions