The references in Java work more like pointers in C++ in some ways. The following C++ snippet would be closer to the Java code, although I wouldn't recommend writing the program that way:
vector<int>* func()
{
vector<int> *a = new vector<int>;
std::cout << "Address of a: " << a << std::endl;
a->push_back(1);
a->push_back(2);
return a;
}
int main()
{
vector<int> *aa = func();
std::cout << "Address of aa: " << aa << std::endl;
delete aa;
}
Result:
Address of a: 01173338
Address of aa: 01173338
For a better idea of how references work in C++, consider the following code:
void addToVector(vector<int>& a) {
a.push_back(2);
}
int main()
{
vector<int> a;
a.push_back(1);
addToVector(a);
std::cout << "Content of a: ";
for (int& i : a)
std::cout << i << " ";
std::cout << endl;
}
Here, a
ends up containing both 1
and 2
because we pass a reference of a
to the function that modifies it. This is similar to how you can pass a reference to a function to modify the object in Java. If you remove the &
in the signature of addToVector
, however, then a
will only end up containing 1
because what was passed to addToVector
was just a copy that is discarded at the end of the function.
Instead of passing around the vector (which will be copied, at least some of it, as the actual content can be moved), the vector is now on the heap and only the pointer is passed. This is like in Java where a copy of the reference is returned rather than a copy of the actual object.