llvm.org GIT mirror llvm / 59a4517
C++11: Beware unnecessary copies with auto It's easy to copy unintentionally when using 'auto', particularly inside range-based for loops. Best practise is to use 'const&' unless there's a good reason not to. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@202729 91177308-0d34-0410-b5e6-96231b3b80d8 Duncan P. N. Exon Smith 6 years ago
1 changed file(s) with 21 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
731731 for these purposes is when the type would have been abstracted away anyways,
732732 often behind a container's typedef such as ``std::vector::iterator``.
733733
734 Beware unnecessary copies with ``auto``
735 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
736
737 The convenience of ``auto`` makes it easy to forget that its default behavior
738 is a copy. Particularly in range-based ``for`` loops, careless copies are
739 expensive.
740
741 As a rule of thumb, use ``const auto &`` unless you need to mutate or copy the
742 result.
743
744 .. code-block:: c++
745
746 // Typically there's no reason to mutate or modify Val.
747 for (const auto &Val : Container) { observe(Val); }
748
749 // Remove the const if you need to modify Val.
750 for (auto &Val : Container) { Val.change(); }
751
752 // Remove the reference if you really want a new copy.
753 for (auto Val : Container) { Val.change(); saveSomewhere(Val); }
754
734755 Style Issues
735756 ============
736757