问题:
When creating local variables, is it correct to use (const) auto&
or auto
?创建局部变量时,使用(const) auto&
或auto
是否正确?
eg:例如:
SomeClass object;
const auto result = object.SomeMethod();
or const auto& result = object.SomeMethod();
或const auto& result = object.SomeMethod();
Where SomeMethod() returns a non-primitive value - maybe another user-defined type. SomeMethod() 返回一个非原始值 - 可能是另一个用户定义的类型。 My understanding is that const auto& result
is correct since the result returned by SomeMethod() would call the copy constructor for the returned type.我的理解是const auto& result
是正确的,因为 SomeMethod() 返回的结果会调用返回类型的复制构造函数。 Please correct me if I am wrong.如果我错了,请纠正我。
What about for primitive types?对于原始类型呢? I assume const auto sum = 1 + 2;
我假设const auto sum = 1 + 2;
is correct.是正确的。
Does this also apply to range based for loops?这是否也适用于基于范围的 for 循环?
for(const auto& object : objects)