C++11: Beware unnecessary copies with auto
authorDuncan P. N. Exon Smith <dexonsmith@apple.com>
Mon, 3 Mar 2014 16:48:47 +0000 (16:48 +0000)
committerDuncan P. N. Exon Smith <dexonsmith@apple.com>
Mon, 3 Mar 2014 16:48:47 +0000 (16:48 +0000)
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

docs/CodingStandards.rst

index edf001aeda01f1908498754e6848cc46f7bcd89e..fa7970221a0a928c820f60041d772a59bf92c92f 100644 (file)
@@ -732,6 +732,27 @@ type is already obvious from the context. Another time when ``auto`` works well
 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
 ============