Debian Codegraph @

clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst

raw
1 .. title:: clang-tidy - bugprone-forwarding-reference-overload
2
3 bugprone-forwarding-reference-overload
4 ======================================
5
6 The check looks for perfect forwarding constructors that can hide copy or move
7 constructors. If a non const lvalue reference is passed to the constructor, the
8 forwarding reference parameter will be a better match than the const reference
9 parameter of the copy constructor, so the perfect forwarding constructor will be
10 called, which can be confusing.
11 For detailed description of this issue see: Scott Meyers, Effective Modern C++,
12 Item 26.
13
14 Consider the following example:
15
16 .. code-block:: c++
17
18 class Person {
19 public:
20 // C1: perfect forwarding ctor
21 template<typename T>
22 explicit Person(T&& n) {}
23
24 // C2: perfect forwarding ctor with parameter default value
25 template<typename T>
26 explicit Person(T&& n, int x = 1) {}
27
28 // C3: perfect forwarding ctor guarded with enable_if
29 template<typename T, typename X = enable_if_t<is_special<T>, void>>
30 explicit Person(T&& n) {}
31
32 // C4: variadic perfect forwarding ctor guarded with enable_if
33 template<typename... A,
34 enable_if_t<is_constructible_v<tuple<string, int>, A&&...>, int> = 0>
35 explicit Person(A&&... a) {}
36
37 // C5: perfect forwarding ctor guarded with requires expression
38 template<typename T>
39 requires requires { is_special<T>; }
40 explicit Person(T&& n) {}
41
42 // C6: perfect forwarding ctor guarded with concept requirement
43 template<Special T>
44 explicit Person(T&& n) {}
45
46 // (possibly compiler generated) copy ctor
47 Person(const Person& rhs);
48 };
49
50 The check warns for constructors C1 and C2, because those can hide copy and move
51 constructors. We suppress warnings if the copy and the move constructors are both
52 disabled (deleted or private), because there is nothing the perfect forwarding
53 constructor could hide in this case. We also suppress warnings for constructors
54 like C3-C6 that are guarded with an ``enable_if`` or a concept, assuming the
55 programmer was aware of the possible hiding.
56
57 Background
58 ----------
59
60 For deciding whether a constructor is guarded with enable_if, we consider the
61 types of the constructor parameters, the default values of template type parameters
62 and the types of non-type template parameters with a default literal value. If any
63 part of these types is ``std::enable_if`` or ``std::enable_if_t``, we assume the
64 constructor is guarded.
65