为何operator new[]会额外分配内存存储数组大小?
operator new[] Allocate Extra Memory for Array Size? Great question—this is one of those C++ design nuances that catches even seasoned developers off guard when they start rolling their own allocators. Let’s break down why this extra prefix exists, and why it’s not something the allocator should handle:
1. delete[] Needs to Know How Many Objects to Destroy
The core issue here is that delete[] isn’t just freeing memory—it’s also responsible for calling the destructor on every object in the array. When you write:
delete[] test_arr;
The compiler has no way to remember at runtime how many test_class objects were created (that info was only known at compile time for your specific new test_class[5] call).
Your allocator only tracks how many bytes were allocated, not how many objects are stored in that memory. It can’t answer "how many instances of test_class live here?" because allocators are designed to be type-agnostic. The extra 8 bytes (size varies by platform) stores the array length explicitly so delete[] can loop through and call the destructor exactly 5 times in your example.
2. Separation of Memory Allocation and Object Construction
C++ intentionally separates memory management from object lifecycle management. Allocators handle the raw memory (allocate/deallocate), while language features like new/delete handle object construction/destruction.
When you use new T[N], it’s a shorthand for:
- Allocate enough memory to hold
Ninstances ofT, plus the extra prefix for the array size. - Call
T’s constructorNtimes on the appropriate chunks of that memory.
The allocator doesn’t know anything about T’s constructor or how many times it needs to be called—that’s the compiler’s job. The prefix is the bridge between the allocation step (handled by your allocator) and the construction/destruction steps (handled by the language runtime).
3. Custom Allocators Don’t Override Language Semantics
Overloading operator new[] to use your stack allocator changes where memory comes from, but not how the new[]/delete[] pair behaves. The C++ standard mandates that delete[] must properly destroy all elements of the array, which requires knowing the element count.
This metadata (array size) can’t be stored in the allocator because:
- Allocators are meant to be reusable across different types and use cases—they don’t track per-allocation object counts.
- The allocator might not even be aware that the memory is being used for an array (it just sees a byte count request).
Think of it this way: your allocator’s job is to hand you a block of memory of a certain size. The operator new[] wrapper adds the necessary bookkeeping so the language can manage the objects inside that block correctly.
内容的提问来源于stack exchange,提问作者Mike van Dyke

