new operarator c++ code example
Example 1: new c++
MyClass * p1 = new MyClass;
// allocates memory by calling: operator new (sizeof(MyClass))
// and then constructs an object at the newly allocated space
MyClass * p2 = new (std::nothrow) MyClass;
// allocates memory by calling: operator new (sizeof(MyClass),std::nothrow)
// and then constructs an object at the newly allocated space
new (p2) MyClass;
// does not allocate memory -- calls: operator new (sizeof(MyClass),p2)
// but constructs an object at p2
// Notice though that calling this function directly does not construct an
//object:
MyClass * p3 = (MyClass*) ::operator new (sizeof(MyClass));
// allocates memory by calling: operator new (sizeof(MyClass))
// but does not call MyClass's constructor
delete p1;
delete p2;
delete p3;
Example 2: new keyword in cpp
#include <iostream>
#include <string>
using String = std::string;
class Entity
{
private:
String m_Name;
public:
Entity() : m_Name("Unknown") {}
Entity(const String& name) : m_Name(name) {}
const String& GetName() const {
return m_Name;
};
};
int main() {
// new keyword is used to allocate memory on heap
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
int* c = new int[50];
Entity* e1 = new Entity;//new keyword Not allocating only memory but also calling the constructor
Entity* e = new Entity[50];
//usually calling new will call underlined c function malloc
//malloc(50);
Entity* alloc = (Entity*)malloc(sizeof(Entity));//will not call constructor only allocate memory = memory of entity
delete e;//calls a c function free
Entity* e3 = new(c) Entity();//Placement New
}