allocate array on heap c++ code example
Example 1: how to allocate on heap in c++
#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
}
Example 2: heap allocated array in c ++
//Heap array
std::array<myarray, 3> stack_array; // Size must be declared explicitly.VLAs
//Stack array
std::vector<myarray> heap_array (3); // Size is optional.