I'm currently learning C++, and am a bit confused about the concept of returning a reference from a method. Consider the following toy example:
#include <iostream>
#include <vector>
class IntHolder {
private:
std::vector<int> d_values;
public:
IntHolder() {
d_values.push_back(1);
d_values.push_back(2);
d_values.push_back(3);
}
std::vector<int> &values() {
return d_values;
}
};
int main(int argc, char **argv) {
IntHolder h;
std::vector<int> ret_val = h.values();
std::cout << ret_val.size() << std::endl;
ret_val.push_back(4);
ret_val.push_back(5);
std::cout << h.values().size() << std::endl;
return 0;
}
This prints the following to the standard output:
3
3
Since we are returning a reference to d_values
, shouldn't the object returned be the same that is stored in the instance of IntHolder
, and thus when calling h.values()
again, we should see a size of 5?
Since this is not the case, what is the difference between returning a reference to an object or a copy of the object? Is there a difference when you are returning from a method?