RAII Pattern

RAII stands for Resource acquisition is initialisation, and is a common pattern cpp programmers use to avoid memory leaks. This involves wrapping our pointer around an object and deleting it while it is no longer used. In java when we define classes we have constructors, but in cpp we also have destructors, that define what happens when the object falls out of scope. Also in cpp people might not have seen that we can overide operators such as +, -, /, * and also [] which makes it easier to define data structures.

In RAII the new keyword is called during in the constructor, and the delete keyword is called in the destructor.

What RAII let's us do, is automagically manage memory. It is a pattern that enables memory safe programming.

#include <iostream>

// convention for classes note, I like to prefix the members of classes with
// m_ so for example an array member is m_arr
class dynamic_int_array {
    public:
        // constructor
        dynamic_int_array(int size): m_size(size), m_arr(new int[size]) {}

        // make class be referenced like a normal array
        int& operator[](int index) {
            return m_arr[index];
        }

        // destructor
        dynamic_int_array() {
            delete [] m_arr;
        }

    private:
        int* m_arr;
        int m_size;
};

int main() {
    for (;;) {
        int size;
        std::cin >> size;

        dynamic_int_array arr(size);

        for (int i = 0; i < size; i++) {
            arr[i] = i;
        }

        for (int i = 0; i < size; i++) {
            std::cout << arr[i] << std::endl;
        }
    }
    return 0;
    
}

Here we see that when the array falls out of scope, it the memory is managed automagically by the class.