What's the purpose of having a separate “operator new[]”?

前端 未结 5 1856
天涯浪人
天涯浪人 2020-12-11 15:44

Looks like operator new and operator new[] have exactly the same signature:

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


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 16:18

    I've had a reasonably good look at this, and to be blunt there's no reason from an interface standpoint.

    The only possible reason that I can think of is to allow an optimization hint for the implementation, operator new[] is likely to be called upon to allocate larger blocks of memory; but that is a really, really tenuous supposition as you could new a very large structure or new char[2] which doesn't really count as large.

    Note that operator new[] doesn't add any magic extra storage for the array count or anything. It is the job of the new[] operator to work out how much overhead (if any) is needed and to pass the correct byte count to operator new[].

    [A test with gcc indicates that no extra storage is needed by new[] unless the type of the array members being constructed have a non-trivial desctructor.]

    From an interface and contract standpoint (other than require the use of the correct corresponding deallocation function) operator new and operator new[] are identical.

提交回复
热议问题