auto keyword behavior with references

2020-04-05 08:26发布

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
1条回答
地球回转人心会变
2楼-- · 2020-04-05 09:14

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?

查看更多
登录 后发表回答