C++ auto& vs auto

后端 未结 4 569
粉色の甜心
粉色の甜心 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:54

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

    Yes. The auto is nothing more than a compiler-deduced type, so use references where you would normally use references, and local (automatic) copies where you would normally use local copies. Whether or not to use a reference is independent of type deduction.

    Where SomeMethod() returns a non-primitive value - maybe another user-defined type. My understanding is that const auto& result is correct since the result returned by SomeMethod() would call the copy constructor for the returned type. Please correct me if I am wrong.

    Legal? Yes, with the const. Best practice? Probably not, no. At least, not with C++11. Especially not, if the value returned from SomeMethod() is already a temporary. You'll want to learn about C++11 move semantics, copy elision, and return value optimization: https://juanchopanzacpp.wordpress.com/2014/05/11/want-speed-dont-always-pass-by-value/

    http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=199

    https://isocpp.org/wiki/faq/ctors#return-by-value-optimization

    What about for primitive types? I assume const auto sum = 1 + 2; is correct.

    Yes, this is fine.

    Does this also apply to range based for loops?

    for(const auto& object : objects)

    Yes, this is also fine. I write this sort of code at work all the time.

提交回复
热议问题