C++ Programming: Objects, RAII and the STL ยท Memory and Ownership

const Correctness

Mark what must not change: const variables, const references for parameters, and pointers to const.

const_correctness.cpp

#include <iostream>
#include <vector>
using namespace std;

int total(const vector<int> &nums) {      // by const reference: no copy, and no changes allowed
    int sum = 0;
    for (int n : nums) {
        sum += n;
    }
    return sum;
}

int main() {
    const int limit = 3;                  // can never change
    vector<int> data = {1, 2, limit};
    int t = total(data);
    const int *p = &limit;                // pointer to const: *p cannot be changed
    int copy = *p;
    cout << t << " " << copy << endl;
    return 0;
}

Step by step

  1. limit is created on the stack with the value 3.
  2. data is created on the stack with the value [1, 2, 3].
  3. total gets a const reference: no copy, and no way to change data.
  4. sum is created on the stack with the value 0.
  5. n is created on the stack with the value 1.
  6. sum changes from 0 to 1.
  7. n changes from 1 to 2.
  8. sum changes from 1 to 3.
  9. n changes from 2 to 3.
  10. sum changes from 3 to 6.
  11. n goes out of scope and disappears.
  12. The method returns sum.
  13. total() has finished, so its variables are gone. The value it returned, 6, is stored in t.
  14. A pointer to const int: *p can be read but not written.
  15. copy is created on the stack with the value 3.
  16. It prints 6 3.
  17. The method returns 0.
  18. 6 3.