//This is how you use new in c++
int * v = new int[5] //5 elements of type int
// [pointer] = new [type] [size]
#include <iostream>
int main()
{
int* ptr = new int{};
// creates null initialized pointer ptr
delete ptr; // must be cleared manually
// multiple memaddress allocation:
int* p_arr = new int[5]{};
/*
new int[] returns the first elems pointer address
{} initializes with default settings [int{} -> 0], such as MyObj()
[5] -> can be var too, new functionality in modern cpp (new int[var_count])
*/
delete[] p_arr;
}
//placement new in c++
char *buf = new char[sizeof(string)]; // pre-allocated buffer
string *p = new (buf) string("hi"); // placement new
string *q = new string("hi"); // ordinary heap allocation
/*Standard C++ also supports placement new operator, which constructs
an object on a pre-allocated buffer. This is useful when building a
memory pool, a garbage collector or simply when performance and exception
safety are paramount (there's no danger of allocation failure since the memory
has already been allocated, and constructing an object on a pre-allocated
buffer takes less time):
*/
int *a = new int; // cấp phát bộ nhớ cho con trỏ a thuộc kiểu int (4 bytes)
double *arr = new double[5]; // cấp phát 5 ô nhớ cho mảng arr thuộc kiểu double (8 bytes)
int *a = new int;
// do_something;
delete a; // giải phóng con trỏ a đã cấp phát ở trên
double *arr = new double[5];
// do_something;
delete[] arr; // giải phóng mảng arr đã được cấp phát ở trên
// declare an int pointer
int* pointVar;
// dynamically allocate memory
// using the new keyword
pointVar = new int;
// assign value to allocated memory
*pointVar = 45;