What are uses of the C++ construct “placement new”?

和自甴很熟 提交于 2019-11-27 19:51:56

It allows you to do your own memory management. Usually this will get you at best marginally improved performance, but sometimes it's a big win. For example, if your program is using a large number of standard-sized objects, you might well want to make a pool with one large memory allocation.

This sort of thing was also done in C, but since there are no constructors in C it didn't require any language support.

It is also used for embedded programming, where IO devices are often mapped to specific memory addresses

I've used it when constructing objects in a shared memory segment.

Its usefull when building your own container like objects.

For example if you were to create a vector. If you reserve space for a large number of objects you want to allocate the memory with some method that does not invoke the constructor of the object (like new char[sizeof(object) * reserveSize]). Then when people start adding objects into the vector you use placement new to copy them into allocated memory.

template<typename T>
class SillyVectorExample
{
    public:
        SillyVectorExample()
            :reserved(10)
            ,size(0)
            ,data(new char[sizeof(T) * reserved])
        {}
        void push_back(T const& object)
        {
            if (size >= reserved)
            {
                // Do Somthing.
            }
            // Place a copy of the object into the data store.
            new (data+(sizeof(T)*size))  T(object);
            ++size;
        }
        // Add other methods to make sure data is copied and dealllocated correctly.
    private:
        size_t   reserved;
        size_t   size;
        char*    data;
 };

PS. I am not advocating doing this. This is just a simplified example of how containers can work.

Placement new can be used to create type-safe unions, such as Boost's variant.

The union class contains a buffer as big as the biggest type it's specified to contain (and with sufficient alignment). It placement news objects into the buffer as required.

I use this construct when doing C++ in kernel mode.

I use the kernel mode memory allocator and construct the object on the allocated chunk.

All of this is wrapped in classes and functions, but in the end I do a placement new.

Placement new is NOT about making pointers equal (you can just use assignment for that!).

Placement new is for constructing an object at a particular location. There are three ways of constructing an object in C++, and placement new is the only one that gives you explicit control over where that object "lives". This is useful for several things, including shared memory, low-level device I/O, and memory pool/allocator implementation.

With stack allocation, the object is constructed at the top of the stack, wherever that happens to be currently.

With "regular" new, the object is constructed at an effectively arbitrary address on the heap, as managed by the standard library (unless you've overridden operator new).

Placement new says "build me an object at this address specifically", and its implementation is simply an overload of operator new that returns the pointer passed to it, as a means of getting to the remainder of the machinery of the new operator, which constructs an object in the memory returned by the operator new function.

It's also worth noting that the operator new function can be overloaded with arbitrary arguments (just as any other function). These other arguments are passed via the "new(arg 2, arg3, ..., argN)" syntax. Arg1 is always implicitly passed as "sizeof(whatever you're constructing)".

By controlling the exact placement, you can align things in memory and this can sometimes be used to improve CPU fetch/cache performance. Never actually saw it in use, though

It can be useful when paging out memory to a file on the hard drive, which one might do when manipulating large objects.

Placement new allows the developer to allocate the memory from preallocated memory chunk. If the system is larger, then developers go for using placement new. Now I am working on a larger avionics software there we allocate the large memory that is required for the execution of application at the start. And we use the placement new to allocate the memory wherever required. It increases the performance to some amount.

seems to me like a way of allocating an object on the stack ..

I've used it to create objects based on memory containing messages received from the network.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!