c++

C++ placement new operator and memory layout

I have discovered placement new operator when I worked on my Java Virtual Machine. It is useful when you need to dynamically create new instance of class and place it into already allocated memory. This is not so common scenario, but it is necessary if you want to write your own memory allocation system. Here is short code example, how to use it: #include <iostream>using namespace std; classA { int data = 0; A() { cout << "Constructor called" << endl; } ~A() { cout << "Destructor called" << endl; } } int main(int argc, const char** arv) { const int MEMORY_SIZE = 65536; // 64 kB char* rawMemory = new char[MEMORY_SIZE]; // allocating own memory pool A* object = new(rawMemory) A(); // delete object; // CANNOT CALL delete, it would lead to memory corruption object->~A(); // manually call destructor, if you need to get rid of object delete[] rawMemory; // at the end, release ALL allocated memory return 0; } There are some circuimstances for using placement new.

Memory layout

In this blog post I would like to describe memory layout and memory alignment and explain, why it is important. Memory pages In modern computers memory is divided into chunks called pages. On most systems, page is usually around 4 KiB. When you need to allocate some memory, operating system will allocate it to you page by page. Allocated memory is usally rounded to whole pages, so allocating 5 KiB of memory would (mostly) end up allocating 2 pages, 8 KiB in total.