| 1 |
.. title:: clang-tidy - performance-unnecessary-copy-initialization |
| 2 |
|
| 3 |
performance-unnecessary-copy-initialization |
| 4 |
=========================================== |
| 5 |
|
| 6 |
Finds local variable declarations that are initialized using the copy |
| 7 |
constructor of a non-trivially-copyable type but it would suffice to obtain a |
| 8 |
const reference. |
| 9 |
|
| 10 |
The check is only applied if it is safe to replace the copy by a const |
| 11 |
reference. This is the case when the variable is const qualified or when it is |
| 12 |
only used as a const, i.e. only const methods or operators are invoked on it, or |
| 13 |
it is used as const reference or value argument in constructors or function |
| 14 |
calls. |
| 15 |
|
| 16 |
Example: |
| 17 |
|
| 18 |
.. code-block:: c++ |
| 19 |
|
| 20 |
const string& constReference(); |
| 21 |
void Function() { |
| 22 |
// The warning will suggest making this a const reference. |
| 23 |
const string UnnecessaryCopy = constReference(); |
| 24 |
} |
| 25 |
|
| 26 |
struct Foo { |
| 27 |
const string& name() const; |
| 28 |
}; |
| 29 |
void Function(const Foo& foo) { |
| 30 |
// The warning will suggest making this a const reference. |
| 31 |
string UnnecessaryCopy1 = foo.name(); |
| 32 |
UnnecessaryCopy1.find("bar"); |
| 33 |
|
| 34 |
// The warning will suggest making this a const reference. |
| 35 |
string UnnecessaryCopy2 = UnnecessaryCopy1; |
| 36 |
UnnecessaryCopy2.find("bar"); |
| 37 |
} |
| 38 |
|
| 39 |
Options |
| 40 |
------- |
| 41 |
|
| 42 |
.. option:: AllowedTypes |
| 43 |
|
| 44 |
A semicolon-separated list of names of types allowed to be initialized by |
| 45 |
copying. Regular expressions are accepted, e.g. `[Rr]ef(erence)?$` matches |
| 46 |
every type with suffix `Ref`, `ref`, `Reference` and `reference`. The default |
| 47 |
is empty. If a name in the list contains the sequence `::` it is matched |
| 48 |
against the qualified typename (i.e. `namespace::Type`, otherwise it is |
| 49 |
matched against only the type name (i.e. `Type`). |
| 50 |
|
| 51 |
.. option:: ExcludedContainerTypes |
| 52 |
|
| 53 |
A semicolon-separated list of names of types whose methods are allowed to |
| 54 |
return the const reference the variable is copied from. When an expensive to |
| 55 |
copy variable is copy initialized by the return value from a type on this |
| 56 |
list the check does not trigger. This can be used to exclude types known to |
| 57 |
be const incorrect or where the lifetime or immutability of returned |
| 58 |
references is not tied to mutations of the container. An example are view |
| 59 |
types that don't own the underlying data. Like for `AllowedTypes` above, |
| 60 |
regular expressions are accepted and the inclusion of `::` determines whether |
| 61 |
the qualified typename is matched or not. |