Difference between operator new() and operator new[]()?

后端 未结 5 643
礼貌的吻别
礼貌的吻别 2021-01-04 19:40

Is there any difference between fncs: operator new and operator new[] (NOT new and new[] operators)? Except of course call syntax? I\'m asking because I can allocate X numbe

5条回答
  •  有刺的猬
    2021-01-04 20:29

    These functions (operator new etc.) are not generally intended to be called explicitly, but rather used implicitly by new/new[] expressions (symmetrically, operator delete/operator delete[] functions are invoked implicitly by delete/delete[] expressions). An expression that uses new syntax for non-array type will implicitly call operator new function, while an expression with new[] will implicitly call operator new[].

    The important detail here is that an array created by new[] expression will normally be destroyed later by delete[] expression. The latter will need to know the number of objects to destruct (if the objects have non-trivial destructors), i.e. this information has to be passed somehow from new[] expression (when it was known) to the corresponding delete[] expression (when it is needed). In a typical implementation this information is stored inside the block allocated by new[] expression, which is why the memory size requested in the implicit call to operator new[] is normally greater than the product of the number of elements and the element size. The extra space is used to store the household information (number of elements, namely). Later delete[] expression will retrieve that household information and use it to invoke the correct number of destructors before actually freeing the memory by calling operator delete[].

    In your example you are not using any of these mechanisms. In your example you are calling memory allocation functions explicitly, perform construction manually and completely ignore the destruction step (which is OK, since your object has trivial destructor), which means that at least for destruction purposes you don't need to track the exact number of elements in the array. In any case, you keep track of that number manually, in a no variable.

    However, in general case it is not possible. In general case the code will use new[] expressions and delete[] expressions and the number of elements will have to get from new[] to delete[] somehow, meaning that it has to be stored internally, which is why there's a need for a dedicated memory allocation function for arrays - operator new[]. It is not equivalent to a mere operator new with the aforementioned product as size.

提交回复
热议问题