I'm not sure how the auto keyword works. Here is an illustration of my issue:
class Element {
public:
void setA(int a) {
m_a = a;
}
int& a() {
return m_a;
}
private:
int m_a = 0;
};
int main(int argc, char* argv[])
{
Element el;
auto a = el.a();
a = 2;
// displays 2, 0
std::cout << a << ", " << el.a() << std::endl;
int& b = el.a();
b = 3;
// displays 3, 3
std::cout << b << ", " << el.a() << std::endl;
return 0;
}
In my understanding, auto deduce the declaration type from the context in which it is used. Here, it should deduce the a variable as being a reference to an integer since Element:a() is declared as a method returning a reference to an integer.
Instead, it seems that the a variable is a copy of the m_a attribute of the Element class.
I found that I needed to specify auto& to get a reference to the attribute. But I don't really understand why I need to add the ampersand. Shouldn't the compiler know that if a is initialized from a method returning a reference, then it should also be a reference ?