C++ Programming: Objects, RAII and the STL ยท Memory and Ownership
Mark what must not change: const variables, const references for parameters, and pointers to const.
#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;
}limit is created on the stack with the value 3.data is created on the stack with the value [1, 2, 3].sum is created on the stack with the value 0.n is created on the stack with the value 1.sum changes from 0 to 1.n changes from 1 to 2.sum changes from 1 to 3.n changes from 2 to 3.sum changes from 3 to 6.n goes out of scope and disappears.sum.total() has finished, so its variables are gone. The value it returned, 6, is stored in t.copy is created on the stack with the value 3.6 3.0.