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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章