Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ placement new vs. overloading new

Many questions on SO ask about placement new feature of C++ (example 1, example 2) why it is used for. Many answers saying - custom allocating of objects like in pre-allocated spaces.

But question is - why need placement new for this? Won't just overload of operator new for class enough? By overload operator new for class I can exactly control where memory taken from - like call custom allocator. So why would I need placement new for this purpose?

like image 824
zaharpopov Avatar asked Jan 09 '11 09:01

zaharpopov


1 Answers

Placement New

Best example is to think about std::vector

How does std::vector put new items into an array?

When you add a new element to the end of an vector it must use placement new.

class MyVector
{
    char*  data;
    size_t size;

    MyVector() : size(0), data(new char[1000]) {}

    // Placement new copy construction of element into array.
    void push_back(T const& t) { new (data + (sizeof(T) * size)) T(t); ++size;}
};

Remember you can not use assignment or a simple copy because the element does not yet exist in the array (ie the memory space is not yet a T (its value is not defined)) so you must new to create a new T object in the array.

So think of placement new as a means of creating container objects. You can allocate more space than required for the container (and not initialize it). Then use placement new to initialize the elements as they are added.

Overload new

Overloading new allows you to control the space used when object have dynamic storage duration. Maybe your expected usage patterns do not fall under the normal usage patterns and you want to optimize creation/destruction. Maybe you want you want to build your own garbage collection (for a particular type).

The main different is that:

  • Overloading new controls the creation of space for 'dynamic storage duration` objects.
  • Placement new can be used for both dynamic and automatic storage duration objects (I suppose static as well). And is used externally to manage objects.

Overview:

Both are corner cases for the language and rarely used in normal code (I think I have written 2 new overloads and one class that uses placement new (for real production code/ does not include experiments and testing) in 15 years).

By the time you need to use these constructs in real life you will have been working with an experienced team for a couple of years that can validate your design.

like image 198
Martin York Avatar answered Sep 19 '22 00:09

Martin York