Home > Backend Development > C++ > How Much Overhead Does Placement-New Array Allocation Really Have?

How Much Overhead Does Placement-New Array Allocation Really Have?

Mary-Kate Olsen
Release: 2024-12-22 08:40:14
Original
194 people have browsed it

How Much Overhead Does Placement-New Array Allocation Really Have?

Placement-New and Unspecified Array Allocation Overhead

The C 11 standard specifies that the placement-new expression new(buffer) T[5] will result in a call to operator new[](sizeof(T)*5 y,buffer) where x and y are non-negative, unspecified values representing array allocation overhead.

However, this raises a concern when using placement-new with a pre-allocated buffer. If y is greater than 0, the allocated buffer may not be large enough to accommodate the array.

Determining Array Allocation Overhead

As the standard doesn't guarantee the value of y, it's crucial to determine it at runtime. One approach is to create a custom placement-new operator that checks the available buffer space.

inline void* operator new[](std::size_t n, void* p, std::size_t limit)
{
    if (n <= limit)
        std::cout << "life is good\n";
    else
        throw std::bad_alloc();
    return p;
}
Copy after login

By varying the array size and inspecting n in the custom new operator, you can infer the value of y for your platform.

Updated Standard

It's important to note that a defect report fixed this issue in November 2019, making it retroactive to all versions of C . According to the updated standard, the overhead for operator new[](std::size_t, void* p) is always zero.

Therefore, when using the library function operator new[](std::size_t, void*), you can pre-allocate your buffer with the exact size without worrying about unspecified allocation overhead.

The above is the detailed content of How Much Overhead Does Placement-New Array Allocation Really Have?. 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