In C , the placement-new operator allows objects to be constructed directly in memory allocated beforehand. When using placement-new to allocate an array, it is essential to account for the potential unspecified overhead incurred by the operation.
The C 11 standard dictates that the placement-new expression new(buffer) T[5] calls operator new[](sizeof(T)*5 y, buffer). Here, y represents a non-negative overhead value that varies from invocation to invocation. This overhead may impact the size of the preallocated buffer if its value is greater than zero.
Consider the following code snippet:
void* buffer = malloc(sizeof(std::string) * 10); std::string* p = ::new (buffer) std::string[10];
Without prior knowledge of y, it is difficult to determine the appropriate amount of memory to allocate for the buffer. If y is greater than zero, the allocated buffer may be insufficient.
To address this issue, the standard initially left the responsibility of determining the overhead to the implementation details. This uncertainty often forced developers to avoid using operator new[](std::size_t, void* p) or implement their placement array-new operator for run-time checking.
Update
Fortunately, a defect report in 2019 rectified this issue by modifying the standard to specify that y is always zero for operator new[](std::size_t, void* p). This adjustment retroactively applies to all versions of C , providing a consistent and predictable allocation behavior.
Therefore, determining the unspecified overhead is no longer necessary when using placement-new to allocate arrays directly in preallocated memory. Developers can safely utilize operator new[](std::size_t, void* p) without concerns about exceeding the buffer size.
The above is the detailed content of How to Account for Overhead When Using Placement-New for Array Allocation in C ?. For more information, please follow other related articles on the PHP Chinese website!