C++ – Difference Between ::operator new[]() and ::operator new()

c++

I need to construct an array of objects from a previously allocated block of memory. However, I cannot understand in what way ::operator new[]() is different from ::operator new() from the user point of view when allocating that block, since both require the size of the block. In the following example, using either one seems to have the same effect. Am I missing something?

class J {
};

int main() {
    const int size = 5;

    {
        J* a = static_cast<J*> (::operator new[](sizeof (J) * size));
        for (int i = 0; i < size; i++)
            new (&a[i]) J();
        for (int i = 0; i < size; i++)
            a[i].~J();
        ::operator delete[] (a);
    }

    {
        J* a = static_cast<J*> (::operator new(sizeof (J) * size));
        for (int i = 0; i < size; i++)
            new (&a[i]) J();
        for (int i = 0; i < size; i++)
            a[i].~J();
        ::operator delete (a);
    }
}

Best Answer

You're misusing the new.

The point of using new [] is that it calls the constructor for each and every element of the array being allocated. delete[] does the same for the destructors.

You're using placement new and manually calling the constructors and destructors, missing the whole point.