Home >Backend Development >C++ >What Unspecified Overhead Do C 11 Array Placement-New Expressions Incur?

What Unspecified Overhead Do C 11 Array Placement-New Expressions Incur?

DDD
DDDOriginal
2024-12-13 19:07:14423browse

What Unspecified Overhead Do C  11 Array Placement-New Expressions Incur?

Array Placement-New Overhead in the Buffer

The C 11 specification states that all array new-expressions may incur an unspecified overhead, including those that reference the library function operator new[](std::size_t, void*) and other placement allocation functions. This overhead may vary with each invocation of new.

Consider the example:

void* buffer = malloc(sizeof(std::string) * 10);
std::string* p = ::new (buffer) std::string[10];

According to the specification, new (buffer) std::string[10] will invoke operator new[](sizeof(std::string) * 10 y, buffer), where y is an unspecified non-negative overhead value. If y > 0, the pre-allocated buffer will be insufficient.

Determining Required Buffer Size

It is not possible to determine the y overhead value precisely from the standard. Therefore, it is not recommended to use operator new[](std::size_t, void* p) unless you have specific knowledge about the platform's implementation.

If you need to use array placement-new with a pre-allocated buffer, you can create your own placement array new function to check the overhead dynamically:

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;
}

int main()
{
    alignas(std::string) char buffer[100];
    std::string* p = new(buffer, sizeof(buffer)) std::string[3];
}

By varying the array size and inspecting the n value, you can deduce the y overhead for your platform.

The above is the detailed content of What Unspecified Overhead Do C 11 Array Placement-New Expressions Incur?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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