C++ 自動& vs 自動 - C++ auto& vs auto

問題:

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)

解決方案:

參考: https://stackoom.com/en/question/21Htc
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章