Memory Handling

Aliases

int №

This makes a reference to the position of the variable on memory and lets us change its value without having to equate it to a return later in the code.

int e = 8;
int& f = e;
++f; 
// e now equals to 9

void triple(int const &i) {
  i * 3;
}

int main() {
  int num = 5;
  triple(num);
}

When using constants, instead of making the compiler copy the variable again we can just make a reference to its place in memory and save computational costs.

Addresses

This gets the memory address of the variable.

int numero = 5;
cout << &numero;
// Returns: 0x7ffd7caa5b54

Pointers

A pointer is similar to an Alias/Reference. Its an inherited way of doing the same job but in C.

int power = 9000;
int* ptr = &power;
cout << ptr;
// Returns: 0x7ffedc18a93c

You can dereference a pointer to show its value.

cout << *ptr;
// Returns: 9000

Having un-initialized variables is dangerous, specially pointers.

It leads to memory leaks in the program, since the system reserves a range in memory but does not know how much to reserve.

A string reserves 16 bytes of memory, for example.

For cases in which we need an empty pointer, we shall use nullptr.

int* ptr = nullptr;