C++ new int[0] — will it allocate memory?

前端 未结 6 1907
無奈伤痛
無奈伤痛 2020-11-22 06:16

A simple test app:

cout << new int[0] << endl;

outputs:

0x876c0b8

So it looks like it works.

6条回答
  •  逝去的感伤
    2020-11-22 06:44

    From 5.3.4/7

    When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

    From 3.7.3.1/2

    The effect of dereferencing a pointer returned as a request for zero size is undefined.

    Also

    Even if the size of the space requested [by new] is zero, the request can fail.

    That means you can do it, but you can not legally (in a well defined manner across all platforms) dereference the memory that you get - you can only pass it to array delete - and you should delete it.

    Here is an interesting foot-note (i.e not a normative part of the standard, but included for expository purposes) attached to the sentence from 3.7.3.1/2

    [32. The intent is to have operator new() implementable by calling malloc() or calloc(), so the rules are substantially the same. C++ differs from C in requiring a zero request to return a non-null pointer.]

提交回复
热议问题