問題:
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)