C++ Programming: Objects, RAII and the STL · Memory and Ownership
Create values and objects on the heap with new, and release them with delete or delete[].
#include <iostream>
using namespace std;
struct Point {
int x, y;
};
int main() {
int *n = new int(42); // one int on the heap
Point *p = new Point{3, 4}; // one object on the heap
int *arr = new int[3]{7, 8, 9};
p->x = 10;
int total = *n + p->x + arr[2];
delete n; // every new needs a delete
delete p;
delete[] arr; // arrays need delete[]
cout << total << endl;
return 0;
}x in the Point that p points to changes from 3 to 10.total is created on the stack with the value 61.p changes from {x: 10, y: 4} to → freed memory (dangling).arr changes from [7, 8, 9] to → freed memory (dangling).n now points to a different int: -1414812927. p now points to a different Point[3]: [{x: 7797744, y: 0}, {x: 0, y: 0}, {x: 0, y: 0}]. arr now points to a different int[12]: [-1162743571, 0, 0, 0, 0, 0, 7771744, 0, …]. It prints 61.0.