Placement new

For advanced C++ programmers, placement new is nothing special. It can initialize a pre-allocated memory block. However, placement new is more than what you think. It accpets an arbitrary number of arguments of arbitrary types.

See the following code snippet:

#include <iostream>
#include <string>
#include <vector>

void* operator new(size_t sz, const std::string& str, const std::vector& vec) noexcept
{
    try
    {
        std::cerr << str << ' ';
        for(char c : vec)
        {
            std::cerr << c;
        }
    }
    catch(...) {}
    return nullptr;
}

int main()
{
    int* p = new ("Hello", {'w', 'o', 'r', 'l', 'd'}) int;
    return 0;
}

That means, you can put any possible C++ type as the second argument of placement new operators.

Is it used in real cases? In fact, nothrow new operator in standard C++ utilizes this feature. See the implementation in libc++.

Another usage can be found in libgc, a C/C++ garbage collection library.

social