| 1 |
.. title:: clang-tidy - google-explicit-constructor |
| 2 |
|
| 3 |
google-explicit-constructor |
| 4 |
=========================== |
| 5 |
|
| 6 |
|
| 7 |
Checks that constructors callable with a single argument and conversion |
| 8 |
operators are marked explicit to avoid the risk of unintentional implicit |
| 9 |
conversions. |
| 10 |
|
| 11 |
Consider this example: |
| 12 |
|
| 13 |
.. code-block:: c++ |
| 14 |
|
| 15 |
struct S { |
| 16 |
int x; |
| 17 |
operator bool() const { return true; } |
| 18 |
}; |
| 19 |
|
| 20 |
bool f() { |
| 21 |
S a{1}; |
| 22 |
S b{2}; |
| 23 |
return a == b; |
| 24 |
} |
| 25 |
|
| 26 |
The function will return ``true``, since the objects are implicitly converted to |
| 27 |
``bool`` before comparison, which is unlikely to be the intent. |
| 28 |
|
| 29 |
The check will suggest inserting ``explicit`` before the constructor or |
| 30 |
conversion operator declaration. However, copy and move constructors should not |
| 31 |
be explicit, as well as constructors taking a single ``initializer_list`` |
| 32 |
argument. |
| 33 |
|
| 34 |
This code: |
| 35 |
|
| 36 |
.. code-block:: c++ |
| 37 |
|
| 38 |
struct S { |
| 39 |
S(int a); |
| 40 |
explicit S(const S&); |
| 41 |
operator bool() const; |
| 42 |
... |
| 43 |
|
| 44 |
will become |
| 45 |
|
| 46 |
.. code-block:: c++ |
| 47 |
|
| 48 |
struct S { |
| 49 |
explicit S(int a); |
| 50 |
S(const S&); |
| 51 |
explicit operator bool() const; |
| 52 |
... |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
See https://google.github.io/styleguide/cppguide.html#Explicit_Constructors |