具有参考的自动关键字行为 [英] auto keyword behavior with references
问题描述
假设我有一个简单的c ++类,其中包含一个私有成员和一个getter:
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;}
}
现在让我们说我要调用getter来获取我的引用并编辑该值(并在值之前/之后打印)
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;
输出为
1
1
1
3
这与我预期的不完全相同,因为显然m_testValue没有被编辑.确实,如果我将auto替换为double& :
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;
我知道
1
1
3
3
我想要的是什么.
所以问题是:
这是auto
关键字的预期行为还是错误?
如果可以预料,这种行为的原因是什么?这是技术上的限制吗?如果是设计使然,为什么?
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?
推荐答案
推导auto
时,不会推导该参考.它总是推断出价值.如果要引用返回值,则可以使用auto&
,const auto&
或auto&&
.
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&&
.
是的,这是设计使然.实际上,任何其他行为都是非常令人惊讶的.更糟糕的是,很容易在需要时使用参考.但是,假设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?
这篇关于具有参考的自动关键字行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!