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?
When
auto
is deduced, it is not deduced to the reference. It always deduces to the value. If you want to have a reference to returned value, you can haveauto&
,const auto&
orauto&&
.And yes, it is by design. Any other behavior would actually be quite surprising. What is even worse, it is easy to use a reference when you want. However, imagine that
auto
would be actually deduced to the reference. How would you (syntactically) make it a value?