Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto keyword behavior with references

Tags:

c++

auto

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?

like image 616
Basile Perrenoud Avatar asked May 23 '16 14:05

Basile Perrenoud


People also ask

Can auto be a reference C++?

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.

What is the auto keyword used for?

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.

Can auto be a pointer?

Pointers. We can also use auto to declare pointers to other variables.


1 Answers

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?

like image 122
SergeyA Avatar answered Sep 28 '22 19:09

SergeyA