1//placement new in c++
2char *buf = new char[sizeof(string)]; // pre-allocated buffer
3string *p = new (buf) string("hi"); // placement new
4string *q = new string("hi"); // ordinary heap allocation
5/*Standard C++ also supports placement new operator, which constructs
6an object on a pre-allocated buffer. This is useful when building a
7memory pool, a garbage collector or simply when performance and exception
8safety are paramount (there's no danger of allocation failure since the memory
9has already been allocated, and constructing an object on a pre-allocated
10buffer takes less time):
11*/
1#include <iostream>
2#include <string>
3
4using String = std::string;
5class Entity
6{
7private:
8 String m_Name;
9public:
10 Entity() : m_Name("Unknown") {}
11 Entity(const String& name) : m_Name(name) {}
12 const String& GetName() const {
13 return m_Name;
14 };
15};
16int main() {
17 // new keyword is used to allocate memory on heap
18 int* b = new int; // new keyword will call the c function malloc which will allocate on heap memory = data and return a ptr to that plaock of memory
19 int* c = new int[50];
20 Entity* e1 = new Entity;//new keyword Not allocating only memory but also calling the constructor
21 Entity* e = new Entity[50];
22 //usually calling new will call underlined c function malloc
23 //malloc(50);
24 Entity* alloc = (Entity*)malloc(sizeof(Entity));//will not call constructor only allocate memory = memory of entity
25 delete e;//calls a c function free
26 Entity* e3 = new(c) Entity();//Placement New
27}
28