Home > Backend Development > C++ > How Much Memory Should You Pre-allocate for Array Placement-new in C ?

How Much Memory Should You Pre-allocate for Array Placement-new in C ?

Patricia Arquette
Release: 2024-12-21 13:34:13
Original
759 people have browsed it

How Much Memory Should You Pre-allocate for Array Placement-new in C  ?

Array Placement-New: Managing Overhead in Buffer Allocation

The C 11 standard allows for array allocation using placement-new, where the memory location is manually specified. However, an unspecified overhead value, denoted by x and y, may be added to the buffer size during allocation. This raises the question of how to determine the amount of memory to pre-allocate when employing array placement-new.

The standard example provided in 5.3.4 [expr.new] illustrates that new(buffer) std::string[10] will internally call operator new[](sizeof(std::string) * 10 y, buffer). This implies that the overhead value y, if non-zero, could lead to a pre-allocated buffer that is too small.

Amendment: Overhead Elimination for Standard Placement Functions

Recently, a fix was introduced (defect report in November 2019) that eliminates the unspecified overhead y when using the standard placement function operator new[](std::size_t, void* p). This means that the overhead is consistently zero for this particular placement function.

Implications for Custom Placement Functions

While the overhead has been removed for the standard placement function, it remains a potential concern when using custom placement functions. For such cases, it is essential not to rely on a specific overhead value. Instead, it is recommended to implement a custom placement array new function that can dynamically determine the overhead at runtime.

By examining the value of n in a custom placement array new function and comparing it to the specified buffer limit, one can infer the overhead for a specific platform and adjust the buffer allocation accordingly.

Conclusion

When working with array placement-new, it is crucial to be aware of the potential overhead associated with custom placement functions. Implementing a custom placement array new function that can detect the overhead at runtime ensures that the correct amount of memory is allocated and avoids potential allocation failures.

The above is the detailed content of How Much Memory Should You Pre-allocate for Array Placement-new 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