C/C++ Arena

Step 3 of 8

RAII

RAII (Resource Acquisition Is Initialization) means: acquire a resource in a constructor, release it in the destructor. Since destructors always run, you can't forget to clean up, even on early return.

class IntArray {
public:
    IntArray(int n) : data_(new int[n]()), n_(n) {}
    ~IntArray() { delete[] data_; }
    ...
};

new T[n] / delete[] p are C++'s versions of malloc/free for arrays (new T / delete p for one object). The () after new int[n] zero-initializes the elements.

Your turn: finish IntArray: the destructor, plus int size() const, int& at(int i) (returns a reference so callers can write through it) and int sum() const.

Previous: Order of destruction Next: The copy problem