Let's say I have a simple c++ class that contains a private member and a getter:
class MyClass
{
private:
double m_testValue = 1;
public:
double& getTestValue(){return m_testValue;}
}
Now let's say I want to call the getter to get my reference and edit this value (and printing before / after values)
auto testVal = myClassInstance.getTestValue();
std::cout << myClassInstance.getTestValue() << std::endl;
std::cout << testVal << std::endl;
testVal = 3;
std::cout << myClassInstance.getTestValue() << std::endl;
std::cout << testVal << std::endl;
The output is
1
1
1
3
This is not exactly what I expected since apparently, m_testValue wasn't edited. Indeed, if I replace auto with double& :
double& testVal = myClassInstance.getTestValue();
std::cout << myClassInstance.getTestValue() << std::endl;
std::cout << testVal << std::endl;
testVal = 3;
std::cout << myClassInstance.getTestValue() << std::endl;
std::cout << testVal << std::endl;
I get
1
1
3
3
Which is what I want.
So the question is:
Is this the expected behaviour of the auto
keyword or is it a bug?
If this is expected, what is the reason for this behaviour? is it a technical limitation? If it by design and why?