[llvm] r202729 - C++11: Beware unnecessary copies with auto
Duncan P. N. Exon Smith
dexonsmith at apple.com
Mon Mar 3 08:48:47 PST 2014
Author: dexonsmith
Date: Mon Mar 3 10:48:47 2014
New Revision: 202729
URL: http://llvm.org/viewvc/llvm-project?rev=202729&view=rev
Log:
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.
Modified:
llvm/trunk/docs/CodingStandards.rst
Modified: llvm/trunk/docs/CodingStandards.rst
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/docs/CodingStandards.rst?rev=202729&r1=202728&r2=202729&view=diff
==============================================================================
--- llvm/trunk/docs/CodingStandards.rst (original)
+++ llvm/trunk/docs/CodingStandards.rst Mon Mar 3 10:48:47 2014
@@ -732,6 +732,27 @@ type is already obvious from the context
for these purposes is when the type would have been abstracted away anyways,
often behind a container's typedef such as ``std::vector<T>::iterator``.
+Beware unnecessary copies with ``auto``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The convenience of ``auto`` makes it easy to forget that its default behavior
+is a copy. Particularly in range-based ``for`` loops, careless copies are
+expensive.
+
+As a rule of thumb, use ``const auto &`` unless you need to mutate or copy the
+result.
+
+.. code-block:: c++
+
+ // Typically there's no reason to mutate or modify Val.
+ for (const auto &Val : Container) { observe(Val); }
+
+ // Remove the const if you need to modify Val.
+ for (auto &Val : Container) { Val.change(); }
+
+ // Remove the reference if you really want a new copy.
+ for (auto Val : Container) { Val.change(); saveSomewhere(Val); }
+
Style Issues
============
More information about the llvm-commits
mailing list