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?
C++ auto auto, const, and references The auto keyword by itself represents a value type, similar to int or char . It can be modified with the const keyword and the & symbol to represent a const type or a reference type, respectively.
The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.
Pointers. We can also use auto to declare pointers to other variables.
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 have auto&
, const auto&
or auto&&
.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With