Chris Gregory

Home Blog LinkedIn Github

C++ Tutorial 6 - References

12/19/2016

Here we will go over references.

#include <cstdio>
#include <vector>

using namespace std;

int main() {
    vector<int> list;
    list.push_back(13);

    /* Visual Studio: */ getchar();
    return 0;
}

We have declared the variable list as a vector of ints. Then we add the element 13.

What is the value of list and list2 after the following code?

    vector<int> list2 = list;
    list2.push_back(2);

Here we declare list2 and initialize it as a copy of list. The result is that list has the element 13, while list2 has the elements 13 and 2.

When we declare a variable, we declare that it is unique and owns its contents. Therefore, list2 starts out as a unique copy of list and then is modified to be different.

If we simply turn list2 into an reference, it will instead become an alias of our list:

    vector<int>& list2 = list;
    list2.push_back(2);

A reference is signified with an ampersand (&). All usages of this reference will effect the actual variable. Now both lists have the elements 13 and 2.

What does vector contain at the end of test?

void push_back_32(vector<int> vector) {
    vector.push_back(32);
}

void test() {
    vector<int> vector;
    push_back_32(vector);
}

Since push_back_32 takes its parameter by value, as a variable and not a reference, it makes a copy of the vector, inserts 32 into the copy, and then throws the copy away. The vector in test is unaffected by this.

In order to correctly insert 32 into the caller's vector, we must take our parameter by reference:

void push_back_32(vector<int>& vector) {
    vector.push_back(32);
}