Home > Backend Development > C++ > How to Account for Overhead When Using Placement-New for Array Allocation in C ?

How to Account for Overhead When Using Placement-New for Array Allocation in C ?

Barbara Streisand
Release: 2024-12-12 14:12:10
Original
847 people have browsed it

How to Account for Overhead When Using Placement-New for Array Allocation in C  ?

Array Placement-New: Determining Unspecified Overhead in the Buffer

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];
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template