0

If I make a method that return a reference to a member:

class Foo {
    std::vector<int> data;

public:
    std::vector<int> &getData() {
        return data;
    }
};

And then use it to get my data:

int main() {
    Foo f;
    auto myData = f.getData();
}

Why does myData is a std::vector<int> and not an std::vector<int>&? I am expecting to be able to modify the data from the outside so of course I want a reference. Should I explicitly declare myData as a auto&?

Also, in this case, should getData be declared as const? Because the method does not directly change the state of the object but could indirectly.

Jojolatino
  • 696
  • 5
  • 11
  • `auto` deduces the type, it doesn't know if you want a copy or a reference. You must use `auto &` if you want a reference. `getData()` should be declared as `const` if you don't want values to be changed, it would have to return `const` as well. – ChrisMM Nov 19 '19 at 15:49
  • 2
    [Scott Meyers Usefull Video](https://www.youtube.com/watch?v=wQxj20X-tIU). – BiagioF Nov 19 '19 at 15:49
  • Even if data is a `std::vector`, it still a reference. The addresses are same for your 2 vectors. – Matthieu H Nov 19 '19 at 16:59
  • @MatthieuH But if I don't use `auto&`, all the modification I make on `myData` doesn't hold on `Foo::data` so is there a copy that happens even if I return a `std::vector&`? – Jojolatino Nov 19 '19 at 21:24
  • @Jojolatino Holy sh*t, I didn't konw. Now I need to check all my code because I have lot of function which return reference and I often use `auto`. – Matthieu H Nov 26 '19 at 10:19

0 Answers0