Consider the following C++ program:
#include <vector>
#include <iostream>
void add_val(std::vector<int> addTo, int addThis)
{
for(std::vector<int>::iterator it = addTo.begin(); it!=addTo.end(); ++it)
{
*it += addThis;
}
}
void add_ref(std::vector<int>& addTo, int addThis)
{
for(std::vector<int>::iterator it = addTo.begin(); it!=addTo.end(); ++it)
{
*it += addThis;
}
}
int main()
{
std::vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
myVector.push_back(3);
add_val(myVector, 3);
std::cout<<"After add_val"<<std::endl;
for (std::vector<int>::iterator it = myVector.begin(); it!=myVector.end(); ++it)
{
std::cout<<*it<<" ";
}
std::cout<<std::endl;
add_ref(myVector, 3);
std::cout<<"After add_ref"<<std::endl;
for (std::vector<int>::iterator it = myVector.begin(); it!=myVector.end(); ++it)
{
std::cout<<*it<<" ";
}
std::cout<<std::endl;
return 0;
}
The program outputs:
After add_val
1 2 3
After add_ref
4 5 6
Passing the vector
to add_val()
results in the original vector
remaining unchanged, since it is passed by value. Passing the vector
to add_ref()
however, causes the values inside the original vector
to change, since it's passed by reference.
In Python everything is passed by reference. However, a lot of the builtin types (str
, tuple
, int
, float
, etc.) are immutable. This means that any operation you perform on these types results in a new variable being bound in the current scope with the new value. For mutable types (list
, dict
, etc.), you end up with exactly the same result as passing a parameter by reference in C++.