1#include <ext/pb_ds/assoc_container.hpp>
2#include <ext/pb_ds/tree_policy.hpp>
3
4using namespace __gnu_pbds;
5
6typedef tree<int, null_type, less<int>, rb_tree_tag,
7 tree_order_statistics_node_update>
8 ordered_set;
9
10ordered_set ord_set;
11
12int a;
13ord_set.insert(a);
14*ord_set.find_by_order(a);
15ord_set.order_of_key(a);
1 MyClass * p1 = new MyClass;
2 // allocates memory by calling: operator new (sizeof(MyClass))
3 // and then constructs an object at the newly allocated space
4
5 MyClass * p2 = new (std::nothrow) MyClass;
6 // allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
7 // and then constructs an object at the newly allocated space
8
9 new (p2) MyClass;
10 // does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
11 // but constructs an object at p2
12
13 // Notice though that calling this function directly does not construct an
14 //object:
15 MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
16 // allocates memory by calling: operator new (sizeof(MyClass))
17 // but does not call MyClass's constructor
18
19 delete p1;
20 delete p2;
21 delete p3;
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