c++ allocate array on heap 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() {
int* b = new int;
int* c = new int[50];
Entity* e1 = new Entity;
Entity* e = new Entity[50];
Entity* alloc = (Entity*)malloc(sizeof(Entity));
delete e;
Entity* e3 = new(c) Entity();
}
Example 2: heap allocated array in c ++
#include <vector>
std::vector<myarray> bestArray(100);
myarray* heapArray = new myarray[100];
delete [] heapArray;
std::vector<myarray> bestArray{ 1, 2, 3 };
std::vector<myarray> bestArray;
bestArray.push_back(myarray(1));
bestArray.push_back(myarray(2));
bestArray.push_back(myarray(3));