Why is ::operator new[] necessary when ::operator new is enough?

后端 未结 5 988
谎友^
谎友^ 2020-12-24 13:18

As we know, the C++ standard defines two forms of global allocation functions:

void* operator new(size_t);
void* operator new[](size_t);

An

5条回答
  •  無奈伤痛
    2020-12-24 13:46

    The C++ Programming Language: Special Edition p 423 says

    _The operator new() and operator delete() functions allow a user to take over allocation and deallocation of individual objects; operator new[]() and operator delete[]() serve exactly the same role for the allocation and deallocation of arrays.

    Thanks Tony D for correcting my misunderstanding of this nuance.

    Wow, it's not often I'm caught out on something in C++ I'm so certain about - I must have been spending too much time in Objective-C!

    original wrong answer

    It's simple - the new[] form invokes the constructor on every element of a classic C array.

    So it first allocates the space for all the objects, then iterates calling the constructor for each slot.

提交回复
热议问题