C++ auto& vs auto

后端 未结 4 567
粉色の甜心
粉色の甜心 2020-11-28 01:32

When creating local variables, is it correct to use (const) auto& or auto?

e.g.:

SomeClass object;
const auto result =          


        
4条回答
  •  醉话见心
    2020-11-28 01:44

    Yes, it is correct to use auto and auto& for local variables. When getting the return type of a function, it is also correct to use auto&. This applies for range based for loops as well.

    General rules for using auto are:

    • Choose auto x when you want to work with copies.
    • Choose auto &x when you want to work with original items and may modify them.
    • Choose auto const &x when you want to work with original items and will not modify them.

    You can read more about the auto specifier here.

提交回复
热议问题