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.