Skip to content

Instantly share code, notes, and snippets.

@YenForYang
Created June 23, 2021 02:13
Show Gist options
  • Save YenForYang/b8835db0ba307d5143020d13901d294f to your computer and use it in GitHub Desktop.
Save YenForYang/b8835db0ba307d5143020d13901d294f to your computer and use it in GitHub Desktop.
Clang-tidy Checks Docs
.. title:: clang-tidy - abseil-duration-addition
abseil-duration-addition
========================
Check for cases where addition should be performed in the ``absl::Time`` domain.
When adding two values, and one is known to be an ``absl::Time``, we can infer
that the other should be interpreted as an ``absl::Duration`` of a similar
scale, and make that inference explicit.
Examples:
.. code-block:: c++
// Original - Addition in the integer domain
int x;
absl::Time t;
int result = absl::ToUnixSeconds(t) + x;
// Suggestion - Addition in the absl::Time domain
int result = absl::ToUnixSeconds(t + absl::Seconds(x));
.. title:: clang-tidy - abseil-duration-comparison
abseil-duration-comparison
==========================
Checks for comparisons which should be in the ``absl::Duration`` domain instead
of the floating point or integer domains.
N.B.: In cases where a ``Duration`` was being converted to an integer and then
compared against a floating-point value, truncation during the ``Duration``
conversion might yield a different result. In practice this is very rare, and
still indicates a bug which should be fixed.
Examples:
.. code-block:: c++
// Original - Comparison in the floating point domain
double x;
absl::Duration d;
if (x < absl::ToDoubleSeconds(d)) ...
// Suggested - Compare in the absl::Duration domain instead
if (absl::Seconds(x) < d) ...
// Original - Comparison in the integer domain
int x;
absl::Duration d;
if (x < absl::ToInt64Microseconds(d)) ...
// Suggested - Compare in the absl::Duration domain instead
if (absl::Microseconds(x) < d) ...
.. title:: clang-tidy - abseil-duration-conversion-cast
abseil-duration-conversion-cast
===============================
Checks for casts of ``absl::Duration`` conversion functions, and recommends
the right conversion function instead.
Examples:
.. code-block:: c++
// Original - Cast from a double to an integer
absl::Duration d;
int i = static_cast<int>(absl::ToDoubleSeconds(d));
// Suggested - Use the integer conversion function directly.
int i = absl::ToInt64Seconds(d);
// Original - Cast from a double to an integer
absl::Duration d;
double x = static_cast<double>(absl::ToInt64Seconds(d));
// Suggested - Use the integer conversion function directly.
double x = absl::ToDoubleSeconds(d);
Note: In the second example, the suggested fix could yield a different result,
as the conversion to integer could truncate. In practice, this is very rare,
and you should use ``absl::Trunc`` to perform this operation explicitly instead.
.. title:: clang-tidy - abseil-duration-division
abseil-duration-division
========================
``absl::Duration`` arithmetic works like it does with integers. That means that
division of two ``absl::Duration`` objects returns an ``int64`` with any fractional
component truncated toward 0. See `this link <https://github.com/abseil/abseil-cpp/blob/29ff6d4860070bf8fcbd39c8805d0c32d56628a3/absl/time/time.h#L137>`_ for more information on arithmetic with ``absl::Duration``.
For example:
.. code-block:: c++
absl::Duration d = absl::Seconds(3.5);
int64 sec1 = d / absl::Seconds(1); // Truncates toward 0.
int64 sec2 = absl::ToInt64Seconds(d); // Equivalent to division.
assert(sec1 == 3 && sec2 == 3);
double dsec = d / absl::Seconds(1); // WRONG: Still truncates toward 0.
assert(dsec == 3.0);
If you want floating-point division, you should use either the
``absl::FDivDuration()`` function, or one of the unit conversion functions such
as ``absl::ToDoubleSeconds()``. For example:
.. code-block:: c++
absl::Duration d = absl::Seconds(3.5);
double dsec1 = absl::FDivDuration(d, absl::Seconds(1)); // GOOD: No truncation.
double dsec2 = absl::ToDoubleSeconds(d); // GOOD: No truncation.
assert(dsec1 == 3.5 && dsec2 == 3.5);
This check looks for uses of ``absl::Duration`` division that is done in a
floating-point context, and recommends the use of a function that returns a
floating-point value.
.. title:: clang-tidy - abseil-duration-factory-float
abseil-duration-factory-float
=============================
Checks for cases where the floating-point overloads of various
``absl::Duration`` factory functions are called when the more-efficient
integer versions could be used instead.
This check will not suggest fixes for literals which contain fractional
floating point values or non-literals. It will suggest removing
superfluous casts.
Examples:
.. code-block:: c++
// Original - Providing a floating-point literal.
absl::Duration d = absl::Seconds(10.0);
// Suggested - Use an integer instead.
absl::Duration d = absl::Seconds(10);
// Original - Explicitly casting to a floating-point type.
absl::Duration d = absl::Seconds(static_cast<double>(10));
// Suggested - Remove the explicit cast
absl::Duration d = absl::Seconds(10);
.. title:: clang-tidy - abseil-duration-factory-scale
abseil-duration-factory-scale
=============================
Checks for cases where arguments to ``absl::Duration`` factory functions are
scaled internally and could be changed to a different factory function. This
check also looks for arguments with a zero value and suggests using
``absl::ZeroDuration()`` instead.
Examples:
.. code-block:: c++
// Original - Internal multiplication.
int x;
absl::Duration d = absl::Seconds(60 * x);
// Suggested - Use absl::Minutes instead.
absl::Duration d = absl::Minutes(x);
// Original - Internal division.
int y;
absl::Duration d = absl::Milliseconds(y / 1000.);
// Suggested - Use absl:::Seconds instead.
absl::Duration d = absl::Seconds(y);
// Original - Zero-value argument.
absl::Duration d = absl::Hours(0);
// Suggested = Use absl::ZeroDuration instead
absl::Duration d = absl::ZeroDuration();
.. title:: clang-tidy - abseil-duration-subtraction
abseil-duration-subtraction
===========================
Checks for cases where subtraction should be performed in the
``absl::Duration`` domain. When subtracting two values, and the first one is
known to be a conversion from ``absl::Duration``, we can infer that the second
should also be interpreted as an ``absl::Duration``, and make that inference
explicit.
Examples:
.. code-block:: c++
// Original - Subtraction in the double domain
double x;
absl::Duration d;
double result = absl::ToDoubleSeconds(d) - x;
// Suggestion - Subtraction in the absl::Duration domain instead
double result = absl::ToDoubleSeconds(d - absl::Seconds(x));
// Original - Subtraction of two Durations in the double domain
absl::Duration d1, d2;
double result = absl::ToDoubleSeconds(d1) - absl::ToDoubleSeconds(d2);
// Suggestion - Subtraction in the absl::Duration domain instead
double result = absl::ToDoubleSeconds(d1 - d2);
Note: As with other ``clang-tidy`` checks, it is possible that multiple fixes
may overlap (as in the case of nested expressions), so not all occurrences can
be transformed in one run. In particular, this may occur for nested subtraction
expressions. Running ``clang-tidy`` multiple times will find and fix these
overlaps.
.. title:: clang-tidy - abseil-duration-unnecessary-conversion
abseil-duration-unnecessary-conversion
======================================
Finds and fixes cases where ``absl::Duration`` values are being converted to
numeric types and back again.
Floating-point examples:
.. code-block:: c++
// Original - Conversion to double and back again
absl::Duration d1;
absl::Duration d2 = absl::Seconds(absl::ToDoubleSeconds(d1));
// Suggestion - Remove unnecessary conversions
absl::Duration d2 = d1;
// Original - Division to convert to double and back again
absl::Duration d2 = absl::Seconds(absl::FDivDuration(d1, absl::Seconds(1)));
// Suggestion - Remove division and conversion
absl::Duration d2 = d1;
Integer examples:
.. code-block:: c++
// Original - Conversion to integer and back again
absl::Duration d1;
absl::Duration d2 = absl::Hours(absl::ToInt64Hours(d1));
// Suggestion - Remove unnecessary conversions
absl::Duration d2 = d1;
// Original - Integer division followed by conversion
absl::Duration d2 = absl::Seconds(d1 / absl::Seconds(1));
// Suggestion - Remove division and conversion
absl::Duration d2 = d1;
Unwrapping scalar operations:
.. code-block:: c++
// Original - Multiplication by a scalar
absl::Duration d1;
absl::Duration d2 = absl::Seconds(absl::ToInt64Seconds(d1) * 2);
// Suggestion - Remove unnecessary conversion
absl::Duration d2 = d1 * 2;
Note: Converting to an integer and back to an ``absl::Duration`` might be a
truncating operation if the value is not aligned to the scale of conversion.
In the rare case where this is the intended result, callers should use
``absl::Trunc`` to truncate explicitly.
.. title:: clang-tidy - abseil-faster-strsplit-delimiter
abseil-faster-strsplit-delimiter
================================
Finds instances of ``absl::StrSplit()`` or ``absl::MaxSplits()`` where the
delimiter is a single character string literal and replaces with a character.
The check will offer a suggestion to change the string literal into a character.
It will also catch code using ``absl::ByAnyChar()`` for just a single character
and will transform that into a single character as well.
These changes will give the same result, but using characters rather than
single character string literals is more efficient and readable.
Examples:
.. code-block:: c++
// Original - the argument is a string literal.
for (auto piece : absl::StrSplit(str, "B")) {
// Suggested - the argument is a character, which causes the more efficient
// overload of absl::StrSplit() to be used.
for (auto piece : absl::StrSplit(str, 'B')) {
// Original - the argument is a string literal inside absl::ByAnyChar call.
for (auto piece : absl::StrSplit(str, absl::ByAnyChar("B"))) {
// Suggested - the argument is a character, which causes the more efficient
// overload of absl::StrSplit() to be used and we do not need absl::ByAnyChar
// anymore.
for (auto piece : absl::StrSplit(str, 'B')) {
// Original - the argument is a string literal inside absl::MaxSplits call.
for (auto piece : absl::StrSplit(str, absl::MaxSplits("B", 1))) {
// Suggested - the argument is a character, which causes the more efficient
// overload of absl::StrSplit() to be used.
for (auto piece : absl::StrSplit(str, absl::MaxSplits('B', 1))) {
subl.. title:: clang-tidy - abseil-no-internal-dependencies
abseil-no-internal-dependencies
===============================
Warns if code using Abseil depends on internal details. If something is in a
namespace that includes the word “internal”, code is not allowed to depend upon
it beaucse it’s an implementation detail. They cannot friend it, include it,
you mention it or refer to it in any way. Doing so violates Abseil's
compatibility guidelines and may result in breakage. See
https://abseil.io/about/compatibility for more information.
The following cases will result in warnings:
.. code-block:: c++
absl::strings_internal::foo();
// warning triggered on this line
class foo {
friend struct absl::container_internal::faa;
// warning triggered on this line
};
absl::memory_internal::MakeUniqueResult();
// warning triggered on this line
.. title:: clang-tidy - abseil-no-namespace
abseil-no-namespace
===================
Ensures code does not open ``namespace absl`` as that violates Abseil's
compatibility guidelines. Code should not open ``namespace absl`` as that
conflicts with Abseil's compatibility guidelines and may result in breakage.
Any code that uses:
.. code-block:: c++
namespace absl {
...
}
will be prompted with a warning.
See `the full Abseil compatibility guidelines <https://
abseil.io/about/compatibility>`_ for more information.
.. title:: clang-tidy - abseil-redundant-strcat-calls
abseil-redundant-strcat-calls
=============================
Suggests removal of unnecessary calls to ``absl::StrCat`` when the result is
being passed to another call to ``absl::StrCat`` or ``absl::StrAppend``.
The extra calls cause unnecessary temporary strings to be constructed. Removing
them makes the code smaller and faster.
Examples:
.. code-block:: c++
std::string s = absl::StrCat("A", absl::StrCat("B", absl::StrCat("C", "D")));
//before
std::string s = absl::StrCat("A", "B", "C", "D");
//after
absl::StrAppend(&s, absl::StrCat("E", "F", "G"));
//before
absl::StrAppend(&s, "E", "F", "G");
//after
.. title:: clang-tidy - abseil-str-cat-append
abseil-str-cat-append
=====================
Flags uses of ``absl::StrCat()`` to append to a ``std::string``. Suggests
``absl::StrAppend()`` should be used instead.
The extra calls cause unnecessary temporary strings to be constructed. Removing
them makes the code smaller and faster.
.. code-block:: c++
a = absl::StrCat(a, b); // Use absl::StrAppend(&a, b) instead.
Does not diagnose cases where ``absl::StrCat()`` is used as a template
argument for a functor.
.. title:: clang-tidy - abseil-string-find-startswith
abseil-string-find-startswith
=============================
Checks whether a ``std::string::find()`` result is compared with 0, and
suggests replacing with ``absl::StartsWith()``. This is both a readability and
performance issue.
.. code-block:: c++
string s = "...";
if (s.find("Hello World") == 0) { /* do something */ }
becomes
.. code-block:: c++
string s = "...";
if (absl::StartsWith(s, "Hello World")) { /* do something */ }
Options
-------
.. option:: StringLikeClasses
Semicolon-separated list of names of string-like classes. By default only
``std::basic_string`` is considered. The list of methods to considered is
fixed.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: AbseilStringsMatchHeader
The location of Abseil's ``strings/match.h``. Defaults to
``absl/strings/match.h``.
.. title:: clang-tidy - abseil-string-find-str-contains
abseil-string-find-str-contains
===============================
Finds ``s.find(...) == string::npos`` comparisons (for various string-like types)
and suggests replacing with ``absl::StrContains()``.
This improves readability and reduces the likelihood of accidentally mixing
``find()`` and ``npos`` from different string-like types.
By default, "string-like types" includes ``::std::basic_string``,
``::std::basic_string_view``, and ``::absl::string_view``. See the
StringLikeClasses option to change this.
.. code-block:: c++
std::string s = "...";
if (s.find("Hello World") == std::string::npos) { /* do something */ }
absl::string_view a = "...";
if (absl::string_view::npos != a.find("Hello World")) { /* do something */ }
becomes
.. code-block:: c++
std::string s = "...";
if (!absl::StrContains(s, "Hello World")) { /* do something */ }
absl::string_view a = "...";
if (absl::StrContains(a, "Hello World")) { /* do something */ }
Options
-------
.. option:: StringLikeClasses
Semicolon-separated list of names of string-like classes. By default includes
``::std::basic_string``, ``::std::basic_string_view``, and
``::absl::string_view``.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: AbseilStringsMatchHeader
The location of Abseil's ``strings/match.h``. Defaults to
``absl/strings/match.h``.
.. title:: clang-tidy - abseil-time-comparison
abseil-time-comparison
======================
Prefer comparisons in the ``absl::Time`` domain instead of the integer domain.
N.B.: In cases where an ``absl::Time`` is being converted to an integer,
alignment may occur. If the comparison depends on this alignment, doing the
comparison in the ``absl::Time`` domain may yield a different result. In
practice this is very rare, and still indicates a bug which should be fixed.
Examples:
.. code-block:: c++
// Original - Comparison in the integer domain
int x;
absl::Time t;
if (x < absl::ToUnixSeconds(t)) ...
// Suggested - Compare in the absl::Time domain instead
if (absl::FromUnixSeconds(x) < t) ...
.. title:: clang-tidy - abseil-time-subtraction
abseil-time-subtraction
=======================
Finds and fixes ``absl::Time`` subtraction expressions to do subtraction
in the Time domain instead of the numeric domain.
There are two cases of Time subtraction in which deduce additional type
information:
- When the result is an ``absl::Duration`` and the first argument is an
``absl::Time``.
- When the second argument is a ``absl::Time``.
In the first case, we must know the result of the operation, since without that
the second operand could be either an ``absl::Time`` or an ``absl::Duration``.
In the second case, the first operand *must* be an ``absl::Time``, because
subtracting an ``absl::Time`` from an ``absl::Duration`` is not defined.
Examples:
.. code-block:: c++
int x;
absl::Time t;
// Original - absl::Duration result and first operand is a absl::Time.
absl::Duration d = absl::Seconds(absl::ToUnixSeconds(t) - x);
// Suggestion - Perform subtraction in the Time domain instead.
absl::Duration d = t - absl::FromUnixSeconds(x);
// Original - Second operand is an absl::Time.
int i = x - absl::ToUnixSeconds(t);
// Suggestion - Perform subtraction in the Time domain instead.
int i = absl::ToInt64Seconds(absl::FromUnixSeconds(x) - t);
.. title:: clang-tidy - abseil-upgrade-duration-conversions
abseil-upgrade-duration-conversions
===================================
Finds calls to ``absl::Duration`` arithmetic operators and factories whose
argument needs an explicit cast to continue compiling after upcoming API
changes.
The operators ``*=``, ``/=``, ``*``, and ``/`` for ``absl::Duration`` currently
accept an argument of class type that is convertible to an arithmetic type. Such
a call currently converts the value to an ``int64_t``, even in a case such as
``std::atomic<float>`` that would result in lossy conversion.
Additionally, the ``absl::Duration`` factory functions (``absl::Hours``,
``absl::Minutes``, etc) currently accept an ``int64_t`` or a floating-point
type. Similar to the arithmetic operators, calls with an argument of class type
that is convertible to an arithmetic type go through the ``int64_t`` path.
These operators and factories will be changed to only accept arithmetic types to
prevent unintended behavior. After these changes are released, passing an
argument of class type will no longer compile, even if the type is implicitly
convertible to an arithmetic type.
Here are example fixes created by this check:
.. code-block:: c++
std::atomic<int> a;
absl::Duration d = absl::Milliseconds(a);
d *= a;
becomes
.. code-block:: c++
std::atomic<int> a;
absl::Duration d = absl::Milliseconds(static_cast<int64_t>(a));
d *= static_cast<int64_t>(a);
Note that this check always adds a cast to ``int64_t`` in order to preserve the
current behavior of user code. It is possible that this uncovers unintended
behavior due to types implicitly convertible to a floating-point type.
.. title:: clang-tidy - altera-id-dependent-backward-branch
altera-id-dependent-backward-branch
===================================
Finds ID-dependent variables and fields that are used within loops. This causes
branches to occur inside the loops, and thus leads to performance degradation.
.. code-block:: c++
// The following code will produce a warning because this ID-dependent
// variable is used in a loop condition statement.
int ThreadID = get_local_id(0);
// The following loop will produce a warning because the loop condition
// statement depends on an ID-dependent variable.
for (int i = 0; i < ThreadID; ++i) {
std::cout << i << std::endl;
}
// The following loop will not produce a warning, because the ID-dependent
// variable is not used in the loop condition statement.
for (int i = 0; i < 100; ++i) {
std::cout << ThreadID << std::endl;
}
Based on the `Altera SDK for OpenCL: Best Practices Guide
<https://www.altera.com/en_US/pdfs/literature/hb/opencl-sdk/aocl_optimization_guide.pdf>`_.
.. title:: clang-tidy - altera-kernel-name-restriction
altera-kernel-name-restriction
==============================
Finds kernel files and include directives whose filename is `kernel.cl`,
`Verilog.cl`, or `VHDL.cl`. The check is case insensitive.
Such kernel file names cause the offline compiler to generate intermediate
design files that have the same names as certain internal files, which
leads to a compilation error.
Based on the `Guidelines for Naming the Kernel` section in the
`Intel FPGA SDK for OpenCL Pro Edition: Programming Guide
<https://www.intel.com/content/www/us/en/programmable/documentation/mwh1391807965224.html#ewa1412973930963>`_.
.. title:: clang-tidy - altera-single-work-item-barrier
altera-single-work-item-barrier
===============================
Finds OpenCL kernel functions that call a barrier function but do not call
an ID function (``get_local_id``, ``get_local_id``, ``get_group_id``, or
``get_local_linear_id``).
These kernels may be viable single work-item kernels, but will be forced to
execute as NDRange kernels if using a newer version of the Altera Offline
Compiler (>= v17.01).
If using an older version of the Altera Offline Compiler, these kernel
functions will be treated as single work-item kernels, which could be
inefficient or lead to errors if NDRange semantics were intended.
Based on the `Altera SDK for OpenCL: Best Practices Guide
<https://www.altera.com/en_US/pdfs/literature/hb/opencl-sdk/aocl_optimization_guide.pdf>`_.
Examples:
.. code-block:: c++
// error: function calls barrier but does not call an ID function.
void __kernel barrier_no_id(__global int * foo, int size) {
for (int i = 0; i < 100; i++) {
foo[i] += 5;
}
barrier(CLK_GLOBAL_MEM_FENCE);
}
// ok: function calls barrier and an ID function.
void __kernel barrier_with_id(__global int * foo, int size) {
for (int i = 0; i < 100; i++) {
int tid = get_global_id(0);
foo[tid] += 5;
}
barrier(CLK_GLOBAL_MEM_FENCE);
}
// ok with AOC Version 17.01: the reqd_work_group_size turns this into
// an NDRange.
__attribute__((reqd_work_group_size(2,2,2)))
void __kernel barrier_with_id(__global int * foo, int size) {
for (int i = 0; i < 100; i++) {
foo[tid] += 5;
}
barrier(CLK_GLOBAL_MEM_FENCE);
}
Options
-------
.. option:: AOCVersion
Defines the version of the Altera Offline Compiler. Defaults to ``1600``
(corresponding to version 16.00).
.. title:: clang-tidy - altera-struct-pack-align
altera-struct-pack-align
========================
Finds structs that are inefficiently packed or aligned, and recommends
packing and/or aligning of said structs as needed.
Structs that are not packed take up more space than they should, and accessing
structs that are not well aligned is inefficient.
Fix-its are provided to fix both of these issues by inserting and/or amending
relevant struct attributes.
Based on the `Altera SDK for OpenCL: Best Practices Guide
<https://www.altera.com/en_US/pdfs/literature/hb/opencl-sdk/aocl_optimization_guide.pdf>`_.
.. code-block:: c++
// The following struct is originally aligned to 4 bytes, and thus takes up
// 12 bytes of memory instead of 10. Packing the struct will make it use
// only 10 bytes of memory, and aligning it to 16 bytes will make it
// efficient to access.
struct example {
char a; // 1 byte
double b; // 8 bytes
char c; // 1 byte
};
// The following struct is arranged in such a way that packing is not needed.
// However, it is aligned to 4 bytes instead of 8, and thus needs to be
// explicitly aligned.
struct implicitly_packed_example {
char a; // 1 byte
char b; // 1 byte
char c; // 1 byte
char d; // 1 byte
int e; // 4 bytes
};
// The following struct is explicitly aligned and packed.
struct good_example {
char a; // 1 byte
double b; // 8 bytes
char c; // 1 byte
} __attribute__((packed)) __attribute__((aligned(16));
// Explicitly aligning a struct to the wrong value will result in a warning.
// The following example should be aligned to 16 bytes, not 32.
struct badly_aligned_example {
char a; // 1 byte
double b; // 8 bytes
char c; // 1 byte
} __attribute__((packed)) __attribute__((aligned(32)));
.. title:: clang-tidy - altera-unroll-loops
altera-unroll-loops
===================
Finds inner loops that have not been unrolled, as well as fully unrolled loops
with unknown loop bounds or a large number of iterations.
Unrolling inner loops could improve the performance of OpenCL kernels. However,
if they have unknown loop bounds or a large number of iterations, they cannot
be fully unrolled, and should be partially unrolled.
Notes:
- This check is unable to determine the number of iterations in a ``while`` or
``do..while`` loop; hence if such a loop is fully unrolled, a note is emitted
advising the user to partially unroll instead.
- In ``for`` loops, our check only works with simple arithmetic increments (
``+``, ``-``, ``*``, ``/``). For all other increments, partial unrolling is
advised.
- Depending on the exit condition, the calculations for determining if the
number of iterations is large may be off by 1. This should not be an issue
since the cut-off is generally arbitrary.
Based on the `Altera SDK for OpenCL: Best Practices Guide
<https://www.altera.com/en_US/pdfs/literature/hb/opencl-sdk/aocl_optimization_guide.pdf>`_.
.. code-block:: c++
for (int i = 0; i < 10; i++) { // ok: outer loops should not be unrolled
int j = 0;
do { // warning: this inner do..while loop should be unrolled
j++;
} while (j < 15);
int k = 0;
#pragma unroll
while (k < 20) { // ok: this inner loop is already unrolled
k++;
}
}
int A[1000];
#pragma unroll
// warning: this loop is large and should be partially unrolled
for (int a : A) {
printf("%d", a);
}
#pragma unroll 5
// ok: this loop is large, but is partially unrolled
for (int a : A) {
printf("%d", a);
}
#pragma unroll
// warning: this loop is large and should be partially unrolled
for (int i = 0; i < 1000; ++i) {
printf("%d", i);
}
#pragma unroll 5
// ok: this loop is large, but is partially unrolled
for (int i = 0; i < 1000; ++i) {
printf("%d", i);
}
#pragma unroll
// warning: << operator not supported, recommend partial unrolling
for (int i = 0; i < 1000; i<<1) {
printf("%d", i);
}
std::vector<int> someVector (100, 0);
int i = 0;
#pragma unroll
// note: loop may be large, recommend partial unrolling
while (i < someVector.size()) {
someVector[i]++;
}
#pragma unroll
// note: loop may be large, recommend partial unrolling
while (true) {
printf("In loop");
}
#pragma unroll 5
// ok: loop may be large, but is partially unrolled
while (i < someVector.size()) {
someVector[i]++;
}
Options
-------
.. option:: MaxLoopIterations
Defines the maximum number of loop iterations that a fully unrolled loop
can have. By default, it is set to `100`.
In practice, this refers to the integer value of the upper bound
within the loop statement's condition expression.
.. title:: clang-tidy - android-cloexec-accept
android-cloexec-accept
======================
The usage of ``accept()`` is not recommended, it's better to use ``accept4()``.
Without this flag, an opened sensitive file descriptor would remain open across
a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
accept(sockfd, addr, addrlen);
// becomes
accept4(sockfd, addr, addrlen, SOCK_CLOEXEC);
.. title:: clang-tidy - android-cloexec-accept4
android-cloexec-accept4
=======================
``accept4()`` should include ``SOCK_CLOEXEC`` in its type argument to avoid the
file descriptor leakage. Without this flag, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
accept4(sockfd, addr, addrlen, SOCK_NONBLOCK);
// becomes
accept4(sockfd, addr, addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC);
.. title:: clang-tidy - android-cloexec-creat
android-cloexec-creat
=====================
The usage of ``creat()`` is not recommended, it's better to use ``open()``.
Examples:
.. code-block:: c++
int fd = creat(path, mode);
// becomes
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, mode);
.. title:: clang-tidy - android-cloexec-dup
android-cloexec-dup
===================
The usage of ``dup()`` is not recommended, it's better to use ``fcntl()``,
which can set the close-on-exec flag. Otherwise, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
int fd = dup(oldfd);
// becomes
int fd = fcntl(oldfd, F_DUPFD_CLOEXEC);
.. title:: clang-tidy - android-cloexec-epoll-create
android-cloexec-epoll-create
============================
The usage of ``epoll_create()`` is not recommended, it's better to use
``epoll_create1()``, which allows close-on-exec.
Examples:
.. code-block:: c++
epoll_create(size);
// becomes
epoll_create1(EPOLL_CLOEXEC);
.. title:: clang-tidy - android-cloexec-epoll-create1
android-cloexec-epoll-create1
=============================
``epoll_create1()`` should include ``EPOLL_CLOEXEC`` in its type argument to
avoid the file descriptor leakage. Without this flag, an opened sensitive file
would remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
epoll_create1(0);
// becomes
epoll_create1(EPOLL_CLOEXEC);
.. title:: clang-tidy - android-cloexec-fopen
android-cloexec-fopen
=====================
``fopen()`` should include ``e`` in their mode string; so ``re`` would be
valid. This is equivalent to having set ``FD_CLOEXEC on`` that descriptor.
Examples:
.. code-block:: c++
fopen("fn", "r");
// becomes
fopen("fn", "re");
.. title:: clang-tidy - android-cloexec-inotify-init
android-cloexec-inotify-init
============================
The usage of ``inotify_init()`` is not recommended, it's better to use
``inotify_init1()``.
Examples:
.. code-block:: c++
inotify_init();
// becomes
inotify_init1(IN_CLOEXEC);
.. title:: clang-tidy - android-cloexec-inotify-init1
android-cloexec-inotify-init1
=============================
``inotify_init1()`` should include ``IN_CLOEXEC`` in its type argument to avoid the
file descriptor leakage. Without this flag, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
inotify_init1(IN_NONBLOCK);
// becomes
inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
.. title:: clang-tidy - android-cloexec-memfd-create
android-cloexec-memfd-create
============================
``memfd_create()`` should include ``MFD_CLOEXEC`` in its type argument to avoid
the file descriptor leakage. Without this flag, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
memfd_create(name, MFD_ALLOW_SEALING);
// becomes
memfd_create(name, MFD_ALLOW_SEALING | MFD_CLOEXEC);
.. title:: clang-tidy - android-cloexec-open
android-cloexec-open
====================
A common source of security bugs is code that opens a file without using the
``O_CLOEXEC`` flag. Without that flag, an opened sensitive file would remain
open across a fork+exec to a lower-privileged SELinux domain, leaking that
sensitive data. Open-like functions including ``open()``, ``openat()``, and
``open64()`` should include ``O_CLOEXEC`` in their flags argument.
Examples:
.. code-block:: c++
open("filename", O_RDWR);
open64("filename", O_RDWR);
openat(0, "filename", O_RDWR);
// becomes
open("filename", O_RDWR | O_CLOEXEC);
open64("filename", O_RDWR | O_CLOEXEC);
openat(0, "filename", O_RDWR | O_CLOEXEC);
.. title:: clang-tidy - android-cloexec-pipe
android-cloexec-pipe
====================
This check detects usage of ``pipe()``. Using ``pipe()`` is not recommended, ``pipe2()`` is the
suggested replacement. The check also adds the O_CLOEXEC flag that marks the file descriptor to
be closed in child processes. Without this flag a sensitive file descriptor can be leaked to a
child process, potentially into a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
pipe(pipefd);
Suggested replacement:
.. code-block:: c++
pipe2(pipefd, O_CLOEXEC);
.. title:: clang-tidy - android-cloexec-pipe2
android-cloexec-pipe2
=====================
This checks ensures that pipe2() is called with the O_CLOEXEC flag. The check also
adds the O_CLOEXEC flag that marks the file descriptor to be closed in child processes.
Without this flag a sensitive file descriptor can be leaked to a child process,
potentially into a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
pipe2(pipefd, O_NONBLOCK);
Suggested replacement:
.. code-block:: c++
pipe2(pipefd, O_NONBLOCK | O_CLOEXEC);
.. title:: clang-tidy - android-cloexec-socket
android-cloexec-socket
======================
``socket()`` should include ``SOCK_CLOEXEC`` in its type argument to avoid the
file descriptor leakage. Without this flag, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
socket(domain, type, SOCK_STREAM);
// becomes
socket(domain, type, SOCK_STREAM | SOCK_CLOEXEC);
.. title:: clang-tidy - android-comparison-in-temp-failure-retry
android-comparison-in-temp-failure-retry
========================================
Diagnoses comparisons that appear to be incorrectly placed in the argument to
the ``TEMP_FAILURE_RETRY`` macro. Having such a use is incorrect in the vast
majority of cases, and will often silently defeat the purpose of the
``TEMP_FAILURE_RETRY`` macro.
For context, ``TEMP_FAILURE_RETRY`` is `a convenience macro
<https://www.gnu.org/software/libc/manual/html_node/Interrupted-Primitives.html>`_
provided by both glibc and Bionic. Its purpose is to repeatedly run a syscall
until it either succeeds, or fails for reasons other than being interrupted.
Example buggy usage looks like:
.. code-block:: c
char cs[1];
while (TEMP_FAILURE_RETRY(read(STDIN_FILENO, cs, sizeof(cs)) != 0)) {
// Do something with cs.
}
Because TEMP_FAILURE_RETRY will check for whether the result *of the comparison*
is ``-1``, and retry if so.
If you encounter this, the fix is simple: lift the comparison out of the
``TEMP_FAILURE_RETRY`` argument, like so:
.. code-block:: c
char cs[1];
while (TEMP_FAILURE_RETRY(read(STDIN_FILENO, cs, sizeof(cs))) != 0) {
// Do something with cs.
}
Options
-------
.. option:: RetryMacros
A comma-separated list of the names of retry macros to be checked.
.. title:: clang-tidy - boost-use-to-string
boost-use-to-string
===================
This check finds conversion from integer type like ``int`` to ``std::string`` or
``std::wstring`` using ``boost::lexical_cast``, and replace it with calls to
``std::to_string`` and ``std::to_wstring``.
It doesn't replace conversion from floating points despite the ``to_string``
overloads, because it would change the behaviour.
.. code-block:: c++
auto str = boost::lexical_cast<std::string>(42);
auto wstr = boost::lexical_cast<std::wstring>(2137LL);
// Will be changed to
auto str = std::to_string(42);
auto wstr = std::to_wstring(2137LL);
.. title:: clang-tidy - bugprone-argument-comment
bugprone-argument-comment
=========================
Checks that argument comments match parameter names.
The check understands argument comments in the form ``/*parameter_name=*/``
that are placed right before the argument.
.. code-block:: c++
void f(bool foo);
...
f(/*bar=*/true);
// warning: argument name 'bar' in comment does not match parameter name 'foo'
The check tries to detect typos and suggest automated fixes for them.
Options
-------
.. option:: StrictMode
When `false` (default value), the check will ignore leading and trailing
underscores and case when comparing names -- otherwise they are taken into
account.
.. option:: IgnoreSingleArgument
When `true`, the check will ignore the single argument.
.. option:: CommentBoolLiterals
When `true`, the check will add argument comments in the format
``/*ParameterName=*/`` right before the boolean literal argument.
Before:
.. code-block:: c++
void foo(bool TurnKey, bool PressButton);
foo(true, false);
After:
.. code-block:: c++
void foo(bool TurnKey, bool PressButton);
foo(/*TurnKey=*/true, /*PressButton=*/false);
.. option:: CommentIntegerLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the integer literal argument.
Before:
.. code-block:: c++
void foo(int MeaningOfLife);
foo(42);
After:
.. code-block:: c++
void foo(int MeaningOfLife);
foo(/*MeaningOfLife=*/42);
.. option:: CommentFloatLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the float/double literal argument.
Before:
.. code-block:: c++
void foo(float Pi);
foo(3.14159);
After:
.. code-block:: c++
void foo(float Pi);
foo(/*Pi=*/3.14159);
.. option:: CommentStringLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the string literal argument.
Before:
.. code-block:: c++
void foo(const char *String);
void foo(const wchar_t *WideString);
foo("Hello World");
foo(L"Hello World");
After:
.. code-block:: c++
void foo(const char *String);
void foo(const wchar_t *WideString);
foo(/*String=*/"Hello World");
foo(/*WideString=*/L"Hello World");
.. option:: CommentCharacterLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the character literal argument.
Before:
.. code-block:: c++
void foo(char *Character);
foo('A');
After:
.. code-block:: c++
void foo(char *Character);
foo(/*Character=*/'A');
.. option:: CommentUserDefinedLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the user defined literal argument.
Before:
.. code-block:: c++
void foo(double Distance);
double operator"" _km(long double);
foo(402.0_km);
After:
.. code-block:: c++
void foo(double Distance);
double operator"" _km(long double);
foo(/*Distance=*/402.0_km);
.. option:: CommentNullPtrs
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the nullptr literal argument.
Before:
.. code-block:: c++
void foo(A* Value);
foo(nullptr);
After:
.. code-block:: c++
void foo(A* Value);
foo(/*Value=*/nullptr);
.. title:: clang-tidy - bugprone-assert-side-effect
bugprone-assert-side-effect
===========================
Finds ``assert()`` with side effect.
The condition of ``assert()`` is evaluated only in debug builds so a
condition with side effect can cause different behavior in debug / release
builds.
Options
-------
.. option:: AssertMacros
A comma-separated list of the names of assert macros to be checked.
.. option:: CheckFunctionCalls
Whether to treat non-const member and non-member functions as they produce
side effects. Disabled by default because it can increase the number of false
positive warnings.
.. title:: clang-tidy - bugprone-bad-signal-to-kill-thread
bugprone-bad-signal-to-kill-thread
==================================
Finds ``pthread_kill`` function calls when a thread is terminated by
raising ``SIGTERM`` signal and the signal kills the entire process, not
just the individual thread. Use any signal except ``SIGTERM``.
.. code-block: c++
pthread_kill(thread, SIGTERM);
This check corresponds to the CERT C Coding Standard rule
`POS44-C. Do not use signals to terminate threads
<https://wiki.sei.cmu.edu/confluence/display/c/POS44-C.+Do+not+use+signals+to+terminate+threads>`_.
.. title:: clang-tidy - bugprone-bool-pointer-implicit-conversion
bugprone-bool-pointer-implicit-conversion
=========================================
Checks for conditions based on implicit conversion from a ``bool`` pointer to
``bool``.
Example:
.. code-block:: c++
bool *p;
if (p) {
// Never used in a pointer-specific way.
}
.. title:: clang-tidy - bugprone-branch-clone
bugprone-branch-clone
=====================
Checks for repeated branches in ``if/else if/else`` chains, consecutive
repeated branches in ``switch`` statements and identical true and false
branches in conditional operators.
.. code-block:: c++
if (test_value(x)) {
y++;
do_something(x, y);
} else {
y++;
do_something(x, y);
}
In this simple example (which could arise e.g. as a copy-paste error) the
``then`` and ``else`` branches are identical and the code is equivalent the
following shorter and cleaner code:
.. code-block:: c++
test_value(x); // can be omitted unless it has side effects
y++;
do_something(x, y);
If this is the intended behavior, then there is no reason to use a conditional
statement; otherwise the issue can be solved by fixing the branch that is
handled incorrectly.
The check also detects repeated branches in longer ``if/else if/else`` chains
where it would be even harder to notice the problem.
In ``switch`` statements the check only reports repeated branches when they are
consecutive, because it is relatively common that the ``case:`` labels have
some natural ordering and rearranging them would decrease the readability of
the code. For example:
.. code-block:: c++
switch (ch) {
case 'a':
return 10;
case 'A':
return 10;
case 'b':
return 11;
case 'B':
return 11;
default:
return 10;
}
Here the check reports that the ``'a'`` and ``'A'`` branches are identical
(and that the ``'b'`` and ``'B'`` branches are also identical), but does not
report that the ``default:`` branch is also identical to the first two branches.
If this is indeed the correct behavior, then it could be implemented as:
.. code-block:: c++
switch (ch) {
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
default:
return 10;
}
Here the check does not warn for the repeated ``return 10;``, which is good if
we want to preserve that ``'a'`` is before ``'b'`` and ``default:`` is the last
branch.
Finally, the check also examines conditional operators and reports code like:
.. code-block:: c++
return test_value(x) ? x : x;
Unlike if statements, the check does not detect chains of conditional
operators.
Note: This check also reports situations where branches become identical only
after preprocession.
.. title:: clang-tidy - bugprone-copy-constructor-init
bugprone-copy-constructor-init
==============================
Finds copy constructors where the constructor doesn't call
the copy constructor of the base class.
.. code-block:: c++
class Copyable {
public:
Copyable() = default;
Copyable(const Copyable &) = default;
};
class X2 : public Copyable {
X2(const X2 &other) {} // Copyable(other) is missing
};
Also finds copy constructors where the constructor of
the base class don't have parameter.
.. code-block:: c++
class X4 : public Copyable {
X4(const X4 &other) : Copyable() {} // other is missing
};
The check also suggests a fix-its in some cases.
.. title:: clang-tidy - bugprone-dangling-handle
bugprone-dangling-handle
========================
Detect dangling references in value handles like ``std::string_view``.
These dangling references can be a result of constructing handles from temporary
values, where the temporary is destroyed soon after the handle is created.
Examples:
.. code-block:: c++
string_view View = string(); // View will dangle.
string A;
View = A + "A"; // still dangle.
vector<string_view> V;
V.push_back(string()); // V[0] is dangling.
V.resize(3, string()); // V[1] and V[2] will also dangle.
string_view f() {
// All these return values will dangle.
return string();
string S;
return S;
char Array[10]{};
return Array;
}
Options
-------
.. option:: HandleClasses
A semicolon-separated list of class names that should be treated as handles.
By default only ``std::basic_string_view`` and
``std::experimental::basic_string_view`` are considered.
.. title:: clang-tidy - bugprone-dynamic-static-initializers
bugprone-dynamic-static-initializers
====================================
Finds instances of static variables that are dynamically initialized
in header files.
This can pose problems in certain multithreaded contexts. For example,
when disabling compiler generated synchronization instructions for
static variables initialized at runtime (e.g. by ``-fno-threadsafe-statics``), even if a particular project
takes the necessary precautions to prevent race conditions during
initialization by providing their own synchronization, header files included from other projects may
not. Therefore, such a check is helpful for ensuring that disabling
compiler generated synchronization for static variable initialization will not cause
problems.
Consider the following code:
.. code-block:: c
int foo() {
static int k = bar();
return k;
}
When synchronization of static initialization is disabled, if two threads both call `foo` for the first time, there is the possibility that `k` will be double initialized, creating a race condition.
.. title:: clang-tidy - bugprone-exception-escape
bugprone-exception-escape
=========================
Finds functions which may throw an exception directly or indirectly, but they
should not. The functions which should not throw exceptions are the following:
* Destructors
* Move constructors
* Move assignment operators
* The ``main()`` functions
* ``swap()`` functions
* Functions marked with ``throw()`` or ``noexcept``
* Other functions given as option
A destructor throwing an exception may result in undefined behavior, resource
leaks or unexpected termination of the program. Throwing move constructor or
move assignment also may result in undefined behavior or resource leak. The
``swap()`` operations expected to be non throwing most of the cases and they
are always possible to implement in a non throwing way. Non throwing ``swap()``
operations are also used to create move operations. A throwing ``main()``
function also results in unexpected termination.
WARNING! This check may be expensive on large source files.
Options
-------
.. option:: FunctionsThatShouldNotThrow
Comma separated list containing function names which should not throw. An
example value for this parameter can be ``WinMain`` which adds function
``WinMain()`` in the Windows API to the list of the functions which should
not throw. Default value is an empty string.
.. option:: IgnoredExceptions
Comma separated list containing type names which are not counted as thrown
exceptions in the check. Default value is an empty string.
.. title:: clang-tidy - bugprone-fold-init-type
bugprone-fold-init-type
=======================
The check flags type mismatches in
`folds <https://en.wikipedia.org/wiki/Fold_(higher-order_function)>`_
like ``std::accumulate`` that might result in loss of precision.
``std::accumulate`` folds an input range into an initial value using the type of
the latter, with ``operator+`` by default. This can cause loss of precision
through:
- Truncation: The following code uses a floating point range and an int
initial value, so trucation will happen at every application of ``operator+``
and the result will be `0`, which might not be what the user expected.
.. code-block:: c++
auto a = {0.5f, 0.5f, 0.5f, 0.5f};
return std::accumulate(std::begin(a), std::end(a), 0);
- Overflow: The following code also returns `0`.
.. code-block:: c++
auto a = {65536LL * 65536 * 65536};
return std::accumulate(std::begin(a), std::end(a), 0);
.. title:: clang-tidy - bugprone-forward-declaration-namespace
bugprone-forward-declaration-namespace
======================================
Checks if an unused forward declaration is in a wrong namespace.
The check inspects all unused forward declarations and checks if there is any
declaration/definition with the same name existing, which could indicate that
the forward declaration is in a potentially wrong namespace.
.. code-block:: c++
namespace na { struct A; }
namespace nb { struct A {}; }
nb::A a;
// warning : no definition found for 'A', but a definition with the same name
// 'A' found in another namespace 'nb::'
This check can only generate warnings, but it can't suggest a fix at this point.
.. title:: clang-tidy - bugprone-forwarding-reference-overload
bugprone-forwarding-reference-overload
======================================
The check looks for perfect forwarding constructors that can hide copy or move
constructors. If a non const lvalue reference is passed to the constructor, the
forwarding reference parameter will be a better match than the const reference
parameter of the copy constructor, so the perfect forwarding constructor will be
called, which can be confusing.
For detailed description of this issue see: Scott Meyers, Effective Modern C++,
Item 26.
Consider the following example:
.. code-block:: c++
class Person {
public:
// C1: perfect forwarding ctor
template<typename T>
explicit Person(T&& n) {}
// C2: perfect forwarding ctor with parameter default value
template<typename T>
explicit Person(T&& n, int x = 1) {}
// C3: perfect forwarding ctor guarded with enable_if
template<typename T, typename X = enable_if_t<is_special<T>,void>>
explicit Person(T&& n) {}
// (possibly compiler generated) copy ctor
Person(const Person& rhs);
};
The check warns for constructors C1 and C2, because those can hide copy and move
constructors. We suppress warnings if the copy and the move constructors are both
disabled (deleted or private), because there is nothing the perfect forwarding
constructor could hide in this case. We also suppress warnings for constructors
like C3 that are guarded with an ``enable_if``, assuming the programmer was aware of
the possible hiding.
Background
----------
For deciding whether a constructor is guarded with enable_if, we consider the
default values of the type parameters and the types of the constructor
parameters. If any part of these types is ``std::enable_if`` or ``std::enable_if_t``,
we assume the constructor is guarded.
.. title:: clang-tidy - bugprone-implicit-widening-of-multiplication-result
bugprone-implicit-widening-of-multiplication-result
===================================================
The check diagnoses instances where a result of a multiplication is implicitly
widened, and suggests (with fix-it) to either silence the code by making
widening explicit, or to perform the multiplication in a wider type,
to avoid the widening afterwards.
This is mainly useful when operating on a very large buffers.
For example, consider:
.. code-block:: c++
void zeroinit(char* base, unsigned width, unsigned height) {
for(unsigned row = 0; row != height; ++row) {
for(unsigned col = 0; col != width; ++col) {
char* ptr = base + row * width + col;
*ptr = 0;
}
}
}
This is fine in general, but iff ``width * height`` overflows,
you end up wrapping back to the beginning of ``base``
instead of processing the entire requested buffer.
Indeed, this only matters for pretty large buffers (4GB+),
but that can happen very easily for example in image processing,
where for that to happen you "only" need a ~269MPix image.
Options
-------
.. option:: UseCXXStaticCastsInCppSources
When suggesting fix-its for C++ code, should C++-style ``static_cast<>()``'s
be suggested, or C-style casts. Defaults to ``true``.
.. option:: UseCXXHeadersInCppSources
When suggesting to include the appropriate header in C++ code,
should ``<cstddef>`` header be suggested, or ``<stddef.h>``.
Defaults to ``true``.
Examples:
.. code-block:: c++
long mul(int a, int b) {
return a * b; // warning: performing an implicit widening conversion to type 'long' of a multiplication performed in type 'int'
}
char* ptr_add(char *base, int a, int b) {
return base + a * b; // warning: result of multiplication in type 'int' is used as a pointer offset after an implicit widening conversion to type 'ssize_t'
}
char ptr_subscript(char *base, int a, int b) {
return base[a * b]; // warning: result of multiplication in type 'int' is used as a pointer offset after an implicit widening conversion to type 'ssize_t'
}
.. title:: clang-tidy - bugprone-inaccurate-erase
bugprone-inaccurate-erase
=========================
Checks for inaccurate use of the ``erase()`` method.
Algorithms like ``remove()`` do not actually remove any element from the
container but return an iterator to the first redundant element at the end
of the container. These redundant elements must be removed using the
``erase()`` method. This check warns when not all of the elements will be
removed due to using an inappropriate overload.
For example, the following code erases only one element:
.. code-block:: c++
std::vector<int> xs;
...
xs.erase(std::remove(xs.begin(), xs.end(), 10));
Call the two-argument overload of ``erase()`` to remove the subrange:
.. code-block:: c++
std::vector<int> xs;
...
xs.erase(std::remove(xs.begin(), xs.end(), 10), xs.end());
.. title:: clang-tidy - bugprone-incorrect-roundings
bugprone-incorrect-roundings
============================
Checks the usage of patterns known to produce incorrect rounding.
Programmers often use::
(int)(double_expression + 0.5)
to round the double expression to an integer. The problem with this:
1. It is unnecessarily slow.
2. It is incorrect. The number 0.499999975 (smallest representable float
number below 0.5) rounds to 1.0. Even worse behavior for negative
numbers where both -0.5f and -1.4f both round to 0.0.
.. title:: clang-tidy - bugprone-infinite-loop
bugprone-infinite-loop
======================
Finds obvious infinite loops (loops where the condition variable is not changed
at all).
Finding infinite loops is well-known to be impossible (halting problem).
However, it is possible to detect some obvious infinite loops, for example, if
the loop condition is not changed. This check detects such loops. A loop is
considered infinite if it does not have any loop exit statement (``break``,
``continue``, ``goto``, ``return``, ``throw`` or a call to a function called as
``[[noreturn]]``) and all of the following conditions hold for every variable in
the condition:
- It is a local variable.
- It has no reference or pointer aliases.
- It is not a structure or class member.
Furthermore, the condition must not contain a function call to consider the loop
infinite since functions may return different values for different calls.
For example, the following loop is considered infinite `i` is not changed in
the body:
.. code-block:: c++
int i = 0, j = 0;
while (i < 10) {
++j;
}
.. title:: clang-tidy - bugprone-integer-division
bugprone-integer-division
=========================
Finds cases where integer division in a floating point context is likely to
cause unintended loss of precision.
No reports are made if divisions are part of the following expressions:
- operands of operators expecting integral or bool types,
- call expressions of integral or bool types, and
- explicit cast expressions to integral or bool types,
as these are interpreted as signs of deliberateness from the programmer.
Examples:
.. code-block:: c++
float floatFunc(float);
int intFunc(int);
double d;
int i = 42;
// Warn, floating-point values expected.
d = 32 * 8 / (2 + i);
d = 8 * floatFunc(1 + 7 / 2);
d = i / (1 << 4);
// OK, no integer division.
d = 32 * 8.0 / (2 + i);
d = 8 * floatFunc(1 + 7.0 / 2);
d = (double)i / (1 << 4);
// OK, there are signs of deliberateness.
d = 1 << (i / 2);
d = 9 + intFunc(6 * i / 32);
d = (int)(i / 32) - 8;
.. title:: clang-tidy - bugprone-lambda-function-name
bugprone-lambda-function-name
=============================
Checks for attempts to get the name of a function from within a lambda
expression. The name of a lambda is always something like ``operator()``, which
is almost never what was intended.
Example:
.. code-block:: c++
void FancyFunction() {
[] { printf("Called from %s\n", __func__); }();
[] { printf("Now called from %s\n", __FUNCTION__); }();
}
Output::
Called from operator()
Now called from operator()
Likely intended output::
Called from FancyFunction
Now called from FancyFunction
.. title:: clang-tidy - bugprone-macro-parentheses
bugprone-macro-parentheses
==========================
Finds macros that can have unexpected behaviour due to missing parentheses.
Macros are expanded by the preprocessor as-is. As a result, there can be
unexpected behaviour; operators may be evaluated in unexpected order and
unary operators may become binary operators, etc.
When the replacement list has an expression, it is recommended to surround
it with parentheses. This ensures that the macro result is evaluated
completely before it is used.
It is also recommended to surround macro arguments in the replacement list
with parentheses. This ensures that the argument value is calculated
properly.
.. title:: clang-tidy - bugprone-macro-repeated-side-effects
bugprone-macro-repeated-side-effects
====================================
Checks for repeated argument with side effects in macros.
.. title:: clang-tidy - bugprone-misplaced-operator-in-strlen-in-alloc
bugprone-misplaced-operator-in-strlen-in-alloc
==============================================
Finds cases where ``1`` is added to the string in the argument to ``strlen()``,
``strnlen()``, ``strnlen_s()``, ``wcslen()``, ``wcsnlen()``, and ``wcsnlen_s()``
instead of the result and the value is used as an argument to a memory
allocation function (``malloc()``, ``calloc()``, ``realloc()``, ``alloca()``) or
the ``new[]`` operator in `C++`. The check detects error cases even if one of
these functions (except the ``new[]`` operator) is called by a constant function
pointer. Cases where ``1`` is added both to the parameter and the result of the
``strlen()``-like function are ignored, as are cases where the whole addition is
surrounded by extra parentheses.
`C` example code:
.. code-block:: c
void bad_malloc(char *str) {
char *c = (char*) malloc(strlen(str + 1));
}
The suggested fix is to add ``1`` to the return value of ``strlen()`` and not
to its argument. In the example above the fix would be
.. code-block:: c
char *c = (char*) malloc(strlen(str) + 1);
`C++` example code:
.. code-block:: c++
void bad_new(char *str) {
char *c = new char[strlen(str + 1)];
}
As in the `C` code with the ``malloc()`` function, the suggested fix is to
add ``1`` to the return value of ``strlen()`` and not to its argument. In the
example above the fix would be
.. code-block:: c++
char *c = new char[strlen(str) + 1];
Example for silencing the diagnostic:
.. code-block:: c
void bad_malloc(char *str) {
char *c = (char*) malloc(strlen((str + 1)));
}
.. title:: clang-tidy - bugprone-misplaced-pointer-arithmetic-in-alloc
bugprone-misplaced-pointer-arithmetic-in-alloc
===============================================
Finds cases where an integer expression is added to or subtracted from the
result of a memory allocation function (``malloc()``, ``calloc()``,
``realloc()``, ``alloca()``) instead of its argument. The check detects error
cases even if one of these functions is called by a constant function pointer.
Example code:
.. code-block:: c
void bad_malloc(int n) {
char *p = (char*) malloc(n) + 10;
}
The suggested fix is to add the integer expression to the argument of
``malloc`` and not to its result. In the example above the fix would be
.. code-block:: c
char *p = (char*) malloc(n + 10);
.. title:: clang-tidy - bugprone-misplaced-widening-cast
bugprone-misplaced-widening-cast
================================
This check will warn when there is a cast of a calculation result to a bigger
type. If the intention of the cast is to avoid loss of precision then the cast
is misplaced, and there can be loss of precision. Otherwise the cast is
ineffective.
Example code:
.. code-block:: c++
long f(int x) {
return (long)(x * 1000);
}
The result ``x * 1000`` is first calculated using ``int`` precision. If the
result exceeds ``int`` precision there is loss of precision. Then the result is
casted to ``long``.
If there is no loss of precision then the cast can be removed or you can
explicitly cast to ``int`` instead.
If you want to avoid loss of precision then put the cast in a proper location,
for instance:
.. code-block:: c++
long f(int x) {
return (long)x * 1000;
}
Implicit casts
--------------
Forgetting to place the cast at all is at least as dangerous and at least as
common as misplacing it. If :option:`CheckImplicitCasts` is enabled the check
also detects these cases, for instance:
.. code-block:: c++
long f(int x) {
return x * 1000;
}
Floating point
--------------
Currently warnings are only written for integer conversion. No warning is
written for this code:
.. code-block:: c++
double f(float x) {
return (double)(x * 10.0f);
}
Options
-------
.. option:: CheckImplicitCasts
If `true`, enables detection of implicit casts. Default is `false`.
.. title:: clang-tidy - bugprone-move-forwarding-reference
bugprone-move-forwarding-reference
==================================
Warns if ``std::move`` is called on a forwarding reference, for example:
.. code-block:: c++
template <typename T>
void foo(T&& t) {
bar(std::move(t));
}
`Forwarding references
<http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4164.pdf>`_ should
typically be passed to ``std::forward`` instead of ``std::move``, and this is
the fix that will be suggested.
(A forwarding reference is an rvalue reference of a type that is a deduced
function template argument.)
In this example, the suggested fix would be
.. code-block:: c++
bar(std::forward<T>(t));
Background
----------
Code like the example above is sometimes written with the expectation that
``T&&`` will always end up being an rvalue reference, no matter what type is
deduced for ``T``, and that it is therefore not possible to pass an lvalue to
``foo()``. However, this is not true. Consider this example:
.. code-block:: c++
std::string s = "Hello, world";
foo(s);
This code compiles and, after the call to ``foo()``, ``s`` is left in an
indeterminate state because it has been moved from. This may be surprising to
the caller of ``foo()`` because no ``std::move`` was used when calling
``foo()``.
The reason for this behavior lies in the special rule for template argument
deduction on function templates like ``foo()`` -- i.e. on function templates
that take an rvalue reference argument of a type that is a deduced function
template argument. (See section [temp.deduct.call]/3 in the C++11 standard.)
If ``foo()`` is called on an lvalue (as in the example above), then ``T`` is
deduced to be an lvalue reference. In the example, ``T`` is deduced to be
``std::string &``. The type of the argument ``t`` therefore becomes
``std::string& &&``; by the reference collapsing rules, this collapses to
``std::string&``.
This means that the ``foo(s)`` call passes ``s`` as an lvalue reference, and
``foo()`` ends up moving ``s`` and thereby placing it into an indeterminate
state.
.. title:: clang-tidy - bugprone-multiple-statement-macro
bugprone-multiple-statement-macro
=================================
Detect multiple statement macros that are used in unbraced conditionals. Only
the first statement of the macro will be inside the conditional and the other
ones will be executed unconditionally.
Example:
.. code-block:: c++
#define INCREMENT_TWO(x, y) (x)++; (y)++
if (do_increment)
INCREMENT_TWO(a, b); // (b)++ will be executed unconditionally.
.. title:: clang-tidy - bugprone-no-escape
bugprone-no-escape
==================
Finds pointers with the ``noescape`` attribute that are captured by an
asynchronously-executed block. The block arguments in ``dispatch_async()`` and
``dispatch_after()`` are guaranteed to escape, so it is an error if a pointer with the
``noescape`` attribute is captured by one of these blocks.
The following is an example of an invalid use of the ``noescape`` attribute.
.. code-block:: objc
void foo(__attribute__((noescape)) int *p) {
dispatch_async(queue, ^{
*p = 123;
});
});
.. title:: clang-tidy - bugprone-not-null-terminated-result
bugprone-not-null-terminated-result
===================================
Finds function calls where it is possible to cause a not null-terminated result.
Usually the proper length of a string is ``strlen(src) + 1`` or equal length of
this expression, because the null terminator needs an extra space. Without the
null terminator it can result in undefined behaviour when the string is read.
The following and their respective ``wchar_t`` based functions are checked:
``memcpy``, ``memcpy_s``, ``memchr``, ``memmove``, ``memmove_s``,
``strerror_s``, ``strncmp``, ``strxfrm``
The following is a real-world example where the programmer forgot to increase
the passed third argument, which is ``size_t length``. That is why the length
of the allocated memory is not enough to hold the null terminator.
.. code-block:: c
static char *stringCpy(const std::string &str) {
char *result = reinterpret_cast<char *>(malloc(str.size()));
memcpy(result, str.data(), str.size());
return result;
}
In addition to issuing warnings, fix-it rewrites all the necessary code. It also
tries to adjust the capacity of the destination array:
.. code-block:: c
static char *stringCpy(const std::string &str) {
char *result = reinterpret_cast<char *>(malloc(str.size() + 1));
strcpy(result, str.data());
return result;
}
Note: It cannot guarantee to rewrite every of the path-sensitive memory
allocations.
.. _MemcpyTransformation:
Transformation rules of 'memcpy()'
----------------------------------
It is possible to rewrite the ``memcpy()`` and ``memcpy_s()`` calls as the
following four functions: ``strcpy()``, ``strncpy()``, ``strcpy_s()``,
``strncpy_s()``, where the latter two are the safer versions of the former two.
It rewrites the ``wchar_t`` based memory handler functions respectively.
Rewrite based on the destination array
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- If copy to the destination array cannot overflow [1] the new function should
be the older copy function (ending with ``cpy``), because it is more
efficient than the safe version.
- If copy to the destination array can overflow [1] and
:option:`WantToUseSafeFunctions` is set to `true` and it is possible to
obtain the capacity of the destination array then the new function could be
the safe version (ending with ``cpy_s``).
- If the new function is could be safe version and C++ files are analysed and
the destination array is plain ``char``/``wchar_t`` without ``un/signed`` then
the length of the destination array can be omitted.
- If the new function is could be safe version and the destination array is
``un/signed`` it needs to be casted to plain ``char *``/``wchar_t *``.
[1] It is possible to overflow:
- If the capacity of the destination array is unknown.
- If the given length is equal to the destination array's capacity.
Rewrite based on the length of the source string
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- If the given length is ``strlen(source)`` or equal length of this expression
then the new function should be the older copy function (ending with ``cpy``),
as it is more efficient than the safe version (ending with ``cpy_s``).
- Otherwise we assume that the programmer wanted to copy 'N' characters, so the
new function is ``ncpy``-like which copies 'N' characters.
Transformations with 'strlen()' or equal length of this expression
------------------------------------------------------------------
It transforms the ``wchar_t`` based memory and string handler functions
respectively (where only ``strerror_s`` does not have ``wchar_t`` based alias).
Memory handler functions
^^^^^^^^^^^^^^^^^^^^^^^^
``memcpy``
Please visit the
:ref:`Transformation rules of 'memcpy()'<MemcpyTransformation>` section.
``memchr``
Usually there is a C-style cast and it is needed to be removed, because the
new function ``strchr``'s return type is correct. The given length is going
to be removed.
``memmove``
If safe functions are available the new function is ``memmove_s``, which has
a new second argument which is the length of the destination array, it is
adjusted, and the length of the source string is incremented by one.
If safe functions are not available the given length is incremented by one.
``memmove_s``
The given length is incremented by one.
String handler functions
^^^^^^^^^^^^^^^^^^^^^^^^
``strerror_s``
The given length is incremented by one.
``strncmp``
If the third argument is the first or the second argument's ``length + 1``
it has to be truncated without the ``+ 1`` operation.
``strxfrm``
The given length is incremented by one.
Options
-------
.. option:: WantToUseSafeFunctions
The value `true` specifies that the target environment is considered to
implement '_s' suffixed memory and string handler functions which are safer
than older versions (e.g. 'memcpy_s()'). The default value is `true`.
.. title:: clang-tidy - bugprone-parent-virtual-call
bugprone-parent-virtual-call
============================
Detects and fixes calls to grand-...parent virtual methods instead of calls
to overridden parent's virtual methods.
.. code-block:: c++
struct A {
int virtual foo() {...}
};
struct B: public A {
int foo() override {...}
};
struct C: public B {
int foo() override { A::foo(); }
// ^^^^^^^^
// warning: qualified name A::foo refers to a member overridden in subclass; did you mean 'B'? [bugprone-parent-virtual-call]
};
.. title:: clang-tidy - bugprone-posix-return
bugprone-posix-return
=====================
Checks if any calls to ``pthread_*`` or ``posix_*`` functions
(except ``posix_openpt``) expect negative return values. These functions return
either ``0`` on success or an ``errno`` on failure, which is positive only.
Example buggy usage looks like:
.. code-block:: c
if (posix_fadvise(...) < 0) {
This will never happen as the return value is always non-negative. A simple fix could be:
.. code-block:: c
if (posix_fadvise(...) > 0) {
.. title:: clang-tidy - bugprone-redundant-branch-condition
bugprone-redundant-branch-condition
===================================
Finds condition variables in nested ``if`` statements that were also checked in
the outer ``if`` statement and were not changed.
Simple example:
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
if (onFire)
scream();
}
Here `onFire` is checked both in the outer ``if`` and the inner ``if`` statement
without a possible change between the two checks. The check warns for this code
and suggests removal of the second checking of variable `onFire`.
The checker also detects redundant condition checks if the condition variable
is an operand of a logical "and" (``&&``) or a logical "or" (``||``) operator:
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
if (onFire && peopleInTheBuilding > 0)
scream();
}
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
if (onFire || isCollapsing())
scream();
}
In the first case (logical "and") the suggested fix is to remove the redundant
condition variable and keep the other side of the ``&&``. In the second case
(logical "or") the whole ``if`` is removed similarily to the simple case on the
top.
The condition of the outer ``if`` statement may also be a logical "and" (``&&``)
expression:
.. code-block:: c
bool onFire = isBurning();
if (onFire && fireFighters < 10) {
if (someOtherCondition()) {
if (onFire)
scream();
}
}
The error is also detected if both the outer statement is a logical "and"
(``&&``) and the inner statement is a logical "and" (``&&``) or "or" (``||``).
The inner ``if`` statement does not have to be a direct descendant of the outer
one.
No error is detected if the condition variable may have been changed between the
two checks:
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
tryToExtinguish(onFire);
if (onFire && peopleInTheBuilding > 0)
scream();
}
Every possible change is considered, thus if the condition variable is not
a local variable of the function, it is a volatile or it has an alias (pointer
or reference) then no warning is issued.
Known limitations
^^^^^^^^^^^^^^^^^
The ``else`` branch is not checked currently for negated condition variable:
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
scream();
} else {
if (!onFire) {
continueWork();
}
}
The checker currently only detects redundant checking of single condition
variables. More complex expressions are not checked:
.. code-block:: c
if (peopleInTheBuilding == 1) {
if (peopleInTheBuilding == 1) {
doSomething();
}
}
.. title:: clang-tidy - bugprone-reserved-identifier
bugprone-reserved-identifier
============================
`cert-dcl37-c` and `cert-dcl51-cpp` redirect here as an alias for this check.
Checks for usages of identifiers reserved for use by the implementation.
The C and C++ standards both reserve the following names for such use:
- identifiers that begin with an underscore followed by an uppercase letter;
- identifiers in the global namespace that begin with an underscore.
The C standard additionally reserves names beginning with a double underscore,
while the C++ standard strengthens this to reserve names with a double
underscore occurring anywhere.
Violating the naming rules above results in undefined behavior.
.. code-block:: c++
namespace NS {
void __f(); // name is not allowed in user code
using _Int = int; // same with this
#define cool__macro // also this
}
int _g(); // disallowed in global namespace only
The check can also be inverted, i.e. it can be configured to flag any
identifier that is _not_ a reserved identifier. This mode is for use by e.g.
standard library implementors, to ensure they don't infringe on the user
namespace.
This check does not (yet) check for other reserved names, e.g. macro names
identical to language keywords, and names specifically reserved by language
standards, e.g. C++ 'zombie names' and C future library directions.
This check corresponds to CERT C Coding Standard rule `DCL37-C. Do not declare
or define a reserved identifier
<https://wiki.sei.cmu.edu/confluence/display/c/DCL37-C.+Do+not+declare+or+define+a+reserved+identifier>`_
as well as its C++ counterpart, `DCL51-CPP. Do not declare or define a reserved
identifier
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/DCL51-CPP.+Do+not+declare+or+define+a+reserved+identifier>`_.
Options
-------
.. option:: Invert
If `true`, inverts the check, i.e. flags names that are not reserved.
Default is `false`.
.. option:: AllowedIdentifiers
Semicolon-separated list of names that the check ignores. Default is an
empty list.
.. title:: clang-tidy - bugprone-signal-handler
bugprone-signal-handler
=======================
Finds functions registered as signal handlers that call non asynchronous-safe
functions. Any function that cannot be determined to be an asynchronous-safe
function call is assumed to be non-asynchronous-safe by the checker,
including user functions for which only the declaration is visible.
User function calls with visible definition are checked recursively.
The check handles only C code. Only the function names are considered and the
fact that the function is a system-call, but no other restrictions on the
arguments passed to the functions (the ``signal`` call is allowed without
restrictions).
This check corresponds to the CERT C Coding Standard rule
`SIG30-C. Call only asynchronous-safe functions within signal handlers
<https://www.securecoding.cert.org/confluence/display/c/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers>`_
and has an alias name ``cert-sig30-c``.
.. option:: AsyncSafeFunctionSet
Selects wich set of functions is considered as asynchronous-safe
(and therefore allowed in signal handlers). Value ``minimal`` selects
a minimal set that is defined in the CERT SIG30-C rule and includes functions
``abort()``, ``_Exit()``, ``quick_exit()`` and ``signal()``. Value ``POSIX``
selects a larger set of functions that is listed in POSIX.1-2017 (see `this
link
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_03>`_
for more information).
The function ``quick_exit`` is not included in the shown list. It is
assumable that the reason is that the list was not updated for C11.
The checker includes ``quick_exit`` in the set of safe functions.
Functions registered as exit handlers are not checked.
Default is ``POSIX``.
.. title:: clang-tidy - bugprone-signed-char-misuse
bugprone-signed-char-misuse
===========================
`cert-str34-c` redirects here as an alias for this check. For the CERT alias,
the `DiagnoseSignedUnsignedCharComparisons` option is set to `false`.
Finds those ``signed char`` -> integer conversions which might indicate a
programming error. The basic problem with the ``signed char``, that it might
store the non-ASCII characters as negative values. This behavior can cause a
misunderstanding of the written code both when an explicit and when an
implicit conversion happens.
When the code contains an explicit ``signed char`` -> integer conversion, the
human programmer probably expects that the converted value matches with the
character code (a value from [0..255]), however, the actual value is in
[-128..127] interval. To avoid this kind of misinterpretation, the desired way
of converting from a ``signed char`` to an integer value is converting to
``unsigned char`` first, which stores all the characters in the positive [0..255]
interval which matches the known character codes.
In case of implicit conversion, the programmer might not actually be aware
that a conversion happened and char value is used as an integer. There are
some use cases when this unawareness might lead to a functionally imperfect code.
For example, checking the equality of a ``signed char`` and an ``unsigned char``
variable is something we should avoid in C++ code. During this comparison,
the two variables are converted to integers which have different value ranges.
For ``signed char``, the non-ASCII characters are stored as a value in [-128..-1]
interval, while the same characters are stored in the [128..255] interval for
an ``unsigned char``.
It depends on the actual platform whether plain ``char`` is handled as ``signed char``
by default and so it is caught by this check or not. To change the default behavior
you can use ``-funsigned-char`` and ``-fsigned-char`` compilation options.
Currently, this check warns in the following cases:
- ``signed char`` is assigned to an integer variable
- ``signed char`` and ``unsigned char`` are compared with equality/inequality operator
- ``signed char`` is converted to an integer in the array subscript
See also:
`STR34-C. Cast characters to unsigned char before converting to larger integer sizes
<https://wiki.sei.cmu.edu/confluence/display/c/STR34-C.+Cast+characters+to+unsigned+char+before+converting+to+larger+integer+sizes>`_
A good example from the CERT description when a ``char`` variable is used to
read from a file that might contain non-ASCII characters. The problem comes
up when the code uses the ``-1`` integer value as EOF, while the 255 character
code is also stored as ``-1`` in two's complement form of char type.
See a simple example of this bellow. This code stops not only when it reaches
the end of the file, but also when it gets a character with the 255 code.
.. code-block:: c++
#define EOF (-1)
int read(void) {
char CChar;
int IChar = EOF;
if (readChar(CChar)) {
IChar = CChar;
}
return IChar;
}
A proper way to fix the code above is converting the ``char`` variable to
an ``unsigned char`` value first.
.. code-block:: c++
#define EOF (-1)
int read(void) {
char CChar;
int IChar = EOF;
if (readChar(CChar)) {
IChar = static_cast<unsigned char>(CChar);
}
return IChar;
}
Another use case is checking the equality of two ``char`` variables with
different signedness. Inside the non-ASCII value range this comparison between
a ``signed char`` and an ``unsigned char`` always returns ``false``.
.. code-block:: c++
bool compare(signed char SChar, unsigned char USChar) {
if (SChar == USChar)
return true;
return false;
}
The easiest way to fix this kind of comparison is casting one of the arguments,
so both arguments will have the same type.
.. code-block:: c++
bool compare(signed char SChar, unsigned char USChar) {
if (static_cast<unsigned char>(SChar) == USChar)
return true;
return false;
}
.. option:: CharTypdefsToIgnore
A semicolon-separated list of typedef names. In this list, we can list
typedefs for ``char`` or ``signed char``, which will be ignored by the
check. This is useful when a typedef introduces an integer alias like
``sal_Int8`` or ``int8_t``. In this case, human misinterpretation is not
an issue.
.. option:: DiagnoseSignedUnsignedCharComparisons
When `true`, the check will warn on ``signed char``/``unsigned char`` comparisons,
otherwise these comparisons are ignored. By default, this option is set to `true`.
.. title:: clang-tidy - bugprone-sizeof-container
bugprone-sizeof-container
=========================
The check finds usages of ``sizeof`` on expressions of STL container types. Most
likely the user wanted to use ``.size()`` instead.
All class/struct types declared in namespace ``std::`` having a const ``size()``
method are considered containers, with the exception of ``std::bitset`` and
``std::array``.
Examples:
.. code-block:: c++
std::string s;
int a = 47 + sizeof(s); // warning: sizeof() doesn't return the size of the container. Did you mean .size()?
int b = sizeof(std::string); // no warning, probably intended.
std::string array_of_strings[10];
int c = sizeof(array_of_strings) / sizeof(array_of_strings[0]); // no warning, definitely intended.
std::array<int, 3> std_array;
int d = sizeof(std_array); // no warning, probably intended.
.. title:: clang-tidy - bugprone-sizeof-expression
bugprone-sizeof-expression
==========================
The check finds usages of ``sizeof`` expressions which are most likely errors.
The ``sizeof`` operator yields the size (in bytes) of its operand, which may be
an expression or the parenthesized name of a type. Misuse of this operator may
be leading to errors and possible software vulnerabilities.
Suspicious usage of 'sizeof(K)'
-------------------------------
A common mistake is to query the ``sizeof`` of an integer literal. This is
equivalent to query the size of its type (probably ``int``). The intent of the
programmer was probably to simply get the integer and not its size.
.. code-block:: c++
#define BUFLEN 42
char buf[BUFLEN];
memset(buf, 0, sizeof(BUFLEN)); // sizeof(42) ==> sizeof(int)
Suspicious usage of 'sizeof(expr)'
----------------------------------
In cases, where there is an enum or integer to represent a type, a common
mistake is to query the ``sizeof`` on the integer or enum that represents the
type that should be used by ``sizeof``. This results in the size of the integer
and not of the type the integer represents:
.. code-block:: c++
enum data_type {
FLOAT_TYPE,
DOUBLE_TYPE
};
struct data {
data_type type;
void* buffer;
data_type get_type() {
return type;
}
};
void f(data d, int numElements) {
// should be sizeof(float) or sizeof(double), depending on d.get_type()
int numBytes = numElements * sizeof(d.get_type());
...
}
Suspicious usage of 'sizeof(this)'
----------------------------------
The ``this`` keyword is evaluated to a pointer to an object of a given type.
The expression ``sizeof(this)`` is returning the size of a pointer. The
programmer most likely wanted the size of the object and not the size of the
pointer.
.. code-block:: c++
class Point {
[...]
size_t size() { return sizeof(this); } // should probably be sizeof(*this)
[...]
};
Suspicious usage of 'sizeof(char*)'
-----------------------------------
There is a subtle difference between declaring a string literal with
``char* A = ""`` and ``char A[] = ""``. The first case has the type ``char*``
instead of the aggregate type ``char[]``. Using ``sizeof`` on an object declared
with ``char*`` type is returning the size of a pointer instead of the number of
characters (bytes) in the string literal.
.. code-block:: c++
const char* kMessage = "Hello World!"; // const char kMessage[] = "...";
void getMessage(char* buf) {
memcpy(buf, kMessage, sizeof(kMessage)); // sizeof(char*)
}
Suspicious usage of 'sizeof(A*)'
--------------------------------
A common mistake is to compute the size of a pointer instead of its pointee.
These cases may occur because of explicit cast or implicit conversion.
.. code-block:: c++
int A[10];
memset(A, 0, sizeof(A + 0));
struct Point point;
memset(point, 0, sizeof(&point));
Suspicious usage of 'sizeof(...)/sizeof(...)'
---------------------------------------------
Dividing ``sizeof`` expressions is typically used to retrieve the number of
elements of an aggregate. This check warns on incompatible or suspicious cases.
In the following example, the entity has 10-bytes and is incompatible with the
type ``int`` which has 4 bytes.
.. code-block:: c++
char buf[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // sizeof(buf) => 10
void getMessage(char* dst) {
memcpy(dst, buf, sizeof(buf) / sizeof(int)); // sizeof(int) => 4 [incompatible sizes]
}
In the following example, the expression ``sizeof(Values)`` is returning the
size of ``char*``. One can easily be fooled by its declaration, but in parameter
declaration the size '10' is ignored and the function is receiving a ``char*``.
.. code-block:: c++
char OrderedValues[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
return CompareArray(char Values[10]) {
return memcmp(OrderedValues, Values, sizeof(Values)) == 0; // sizeof(Values) ==> sizeof(char*) [implicit cast to char*]
}
Suspicious 'sizeof' by 'sizeof' expression
------------------------------------------
Multiplying ``sizeof`` expressions typically makes no sense and is probably a
logic error. In the following example, the programmer used ``*`` instead of
``/``.
.. code-block:: c++
const char kMessage[] = "Hello World!";
void getMessage(char* buf) {
memcpy(buf, kMessage, sizeof(kMessage) * sizeof(char)); // sizeof(kMessage) / sizeof(char)
}
This check may trigger on code using the arraysize macro. The following code is
working correctly but should be simplified by using only the ``sizeof``
operator.
.. code-block:: c++
extern Object objects[100];
void InitializeObjects() {
memset(objects, 0, arraysize(objects) * sizeof(Object)); // sizeof(objects)
}
Suspicious usage of 'sizeof(sizeof(...))'
-----------------------------------------
Getting the ``sizeof`` of a ``sizeof`` makes no sense and is typically an error
hidden through macros.
.. code-block:: c++
#define INT_SZ sizeof(int)
int buf[] = { 42 };
void getInt(int* dst) {
memcpy(dst, buf, sizeof(INT_SZ)); // sizeof(sizeof(int)) is suspicious.
}
Options
-------
.. option:: WarnOnSizeOfConstant
When `true`, the check will warn on an expression like
``sizeof(CONSTANT)``. Default is `true`.
.. option:: WarnOnSizeOfIntegerExpression
When `true`, the check will warn on an expression like ``sizeof(expr)``
where the expression results in an integer. Default is `false`.
.. option:: WarnOnSizeOfThis
When `true`, the check will warn on an expression like ``sizeof(this)``.
Default is `true`.
.. option:: WarnOnSizeOfCompareToConstant
When `true`, the check will warn on an expression like
``sizeof(epxr) <= k`` for a suspicious constant `k` while `k` is `0` or
greater than `0x8000`. Default is `true`.
.. title:: clang-tidy - bugprone-spuriously-wake-up-functions
bugprone-spuriously-wake-up-functions
=====================================
Finds ``cnd_wait``, ``cnd_timedwait``, ``wait``, ``wait_for``, or
``wait_until`` function calls when the function is not invoked from a loop
that checks whether a condition predicate holds or the function has a
condition parameter.
.. code-block: c++
if (condition_predicate) {
condition.wait(lk);
}
.. code-block: c
if (condition_predicate) {
if (thrd_success != cnd_wait(&condition, &lock)) {
}
}
This check corresponds to the CERT C++ Coding Standard rule
`CON54-CPP. Wrap functions that can spuriously wake up in a loop
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/CON54-CPP.+Wrap+functions+that+can+spuriously+wake+up+in+a+loop>`_.
and CERT C Coding Standard rule
`CON36-C. Wrap functions that can spuriously wake up in a loop
<https://wiki.sei.cmu.edu/confluence/display/c/CON36-C.+Wrap+functions+that+can+spuriously+wake+up+in+a+loop>`_.
.. title:: clang-tidy - bugprone-string-constructor
bugprone-string-constructor
===========================
Finds string constructors that are suspicious and probably errors.
A common mistake is to swap parameters to the 'fill' string-constructor.
Examples:
.. code-block:: c++
std::string str('x', 50); // should be str(50, 'x')
Calling the string-literal constructor with a length bigger than the literal is
suspicious and adds extra random characters to the string.
Examples:
.. code-block:: c++
std::string("test", 200); // Will include random characters after "test".
std::string_view("test", 200);
Creating an empty string from constructors with parameters is considered
suspicious. The programmer should use the empty constructor instead.
Examples:
.. code-block:: c++
std::string("test", 0); // Creation of an empty string.
std::string_view("test", 0);
Options
-------
.. option:: WarnOnLargeLength
When `true`, the check will warn on a string with a length greater than
:option:`LargeLengthThreshold`. Default is `true`.
.. option:: LargeLengthThreshold
An integer specifying the large length threshold. Default is `0x800000`.
.. option:: StringNames
Default is `::std::basic_string;::std::basic_string_view`.
Semicolon-delimited list of class names to apply this check to.
By default `::std::basic_string` applies to ``std::string`` and
``std::wstring``. Set to e.g. `::std::basic_string;llvm::StringRef;QString`
to perform this check on custom classes.
.. title:: clang-tidy - bugprone-string-integer-assignment
bugprone-string-integer-assignment
==================================
The check finds assignments of an integer to ``std::basic_string<CharT>``
(``std::string``, ``std::wstring``, etc.). The source of the problem is the
following assignment operator of ``std::basic_string<CharT>``:
.. code-block:: c++
basic_string& operator=( CharT ch );
Numeric types can be implicitly casted to character types.
.. code-block:: c++
std::string s;
int x = 5965;
s = 6;
s = x;
Use the appropriate conversion functions or character literals.
.. code-block:: c++
std::string s;
int x = 5965;
s = '6';
s = std::to_string(x);
In order to suppress false positives, use an explicit cast.
.. code-block:: c++
std::string s;
s = static_cast<char>(6);
.. title:: clang-tidy - bugprone-string-literal-with-embedded-nul
bugprone-string-literal-with-embedded-nul
=========================================
Finds occurrences of string literal with embedded NUL character and validates
their usage.
Invalid escaping
----------------
Special characters can be escaped within a string literal by using their
hexadecimal encoding like ``\x42``. A common mistake is to escape them
like this ``\0x42`` where the ``\0`` stands for the NUL character.
.. code-block:: c++
const char* Example[] = "Invalid character: \0x12 should be \x12";
const char* Bytes[] = "\x03\0x02\0x01\0x00\0xFF\0xFF\0xFF";
Truncated literal
-----------------
String-like classes can manipulate strings with embedded NUL as they are keeping
track of the bytes and the length. This is not the case for a ``char*``
(NUL-terminated) string.
A common mistake is to pass a string-literal with embedded NUL to a string
constructor expecting a NUL-terminated string. The bytes after the first NUL
character are truncated.
.. code-block:: c++
std::string str("abc\0def"); // "def" is truncated
str += "\0"; // This statement is doing nothing
if (str == "\0abc") return; // This expression is always true
.. title:: clang-tidy - bugprone-suspicious-enum-usage
bugprone-suspicious-enum-usage
==============================
The checker detects various cases when an enum is probably misused (as a bitmask
).
1. When "ADD" or "bitwise OR" is used between two enum which come from different
types and these types value ranges are not disjoint.
The following cases will be investigated only using :option:`StrictMode`. We
regard the enum as a (suspicious)
bitmask if the three conditions below are true at the same time:
* at most half of the elements of the enum are non pow-of-2 numbers (because of
short enumerations)
* there is another non pow-of-2 number than the enum constant representing all
choices (the result "bitwise OR" operation of all enum elements)
* enum type variable/enumconstant is used as an argument of a `+` or "bitwise OR
" operator
So whenever the non pow-of-2 element is used as a bitmask element we diagnose a
misuse and give a warning.
2. Investigating the right hand side of `+=` and `|=` operator.
3. Check only the enum value side of a `|` and `+` operator if one of them is not
enum val.
4. Check both side of `|` or `+` operator where the enum values are from the
same enum type.
Examples:
.. code-block:: c++
enum { A, B, C };
enum { D, E, F = 5 };
enum { G = 10, H = 11, I = 12 };
unsigned flag;
flag =
A |
H; // OK, disjoint value intervals in the enum types ->probably good use.
flag = B | F; // Warning, have common values so they are probably misused.
// Case 2:
enum Bitmask {
A = 0,
B = 1,
C = 2,
D = 4,
E = 8,
F = 16,
G = 31 // OK, real bitmask.
};
enum Almostbitmask {
AA = 0,
BB = 1,
CC = 2,
DD = 4,
EE = 8,
FF = 16,
GG // Problem, forgot to initialize.
};
unsigned flag = 0;
flag |= E; // OK.
flag |=
EE; // Warning at the decl, and note that it was used here as a bitmask.
Options
-------
.. option:: StrictMode
Default value: 0.
When non-null the suspicious bitmask usage will be investigated additionally
to the different enum usage check.
.. title:: clang-tidy - bugprone-suspicious-include
bugprone-suspicious-include
===========================
The check detects various cases when an include refers to what appears to be an
implementation file, which often leads to hard-to-track-down ODR violations.
Examples:
.. code-block:: c++
#include "Dinosaur.hpp" // OK, .hpp files tend not to have definitions.
#include "Pterodactyl.h" // OK, .h files tend not to have definitions.
#include "Velociraptor.cpp" // Warning, filename is suspicious.
#include_next <stdio.c> // Warning, filename is suspicious.
Options
-------
.. option:: HeaderFileExtensions
Default value: ``";h;hh;hpp;hxx"``
A semicolon-separated list of filename extensions of header files (the
filename extensions should not contain a "." prefix). For extension-less
header files, use an empty string or leave an empty string between ";"
if there are other filename extensions.
.. option:: ImplementationFileExtensions
Default value: ``"c;cc;cpp;cxx"``
Likewise, a semicolon-separated list of filename extensions of
implementation files.
.. title:: clang-tidy - bugprone-suspicious-memset-usage
bugprone-suspicious-memset-usage
================================
This check finds ``memset()`` calls with potential mistakes in their arguments.
Considering the function as ``void* memset(void* destination, int fill_value,
size_t byte_count)``, the following cases are covered:
**Case 1: Fill value is a character ``'0'``**
Filling up a memory area with ASCII code 48 characters is not customary,
possibly integer zeroes were intended instead.
The check offers a replacement of ``'0'`` with ``0``. Memsetting character
pointers with ``'0'`` is allowed.
**Case 2: Fill value is truncated**
Memset converts ``fill_value`` to ``unsigned char`` before using it. If
``fill_value`` is out of unsigned character range, it gets truncated
and memory will not contain the desired pattern.
**Case 3: Byte count is zero**
Calling memset with a literal zero in its ``byte_count`` argument is likely
to be unintended and swapped with ``fill_value``. The check offers to swap
these two arguments.
Corresponding cpplint.py check name: ``runtime/memset``.
Examples:
.. code-block:: c++
void foo() {
int i[5] = {1, 2, 3, 4, 5};
int *ip = i;
char c = '1';
char *cp = &c;
int v = 0;
// Case 1
memset(ip, '0', 1); // suspicious
memset(cp, '0', 1); // OK
// Case 2
memset(ip, 0xabcd, 1); // fill value gets truncated
memset(ip, 0x00, 1); // OK
// Case 3
memset(ip, sizeof(int), v); // zero length, potentially swapped
memset(ip, 0, 1); // OK
}
.. title:: clang-tidy - bugprone-suspicious-missing-comma
bugprone-suspicious-missing-comma
=================================
String literals placed side-by-side are concatenated at translation phase 6
(after the preprocessor). This feature is used to represent long string
literal on multiple lines.
For instance, the following declarations are equivalent:
.. code-block:: c++
const char* A[] = "This is a test";
const char* B[] = "This" " is a " "test";
A common mistake done by programmers is to forget a comma between two string
literals in an array initializer list.
.. code-block:: c++
const char* Test[] = {
"line 1",
"line 2" // Missing comma!
"line 3",
"line 4",
"line 5"
};
The array contains the string "line 2line3" at offset 1 (i.e. Test[1]). Clang
won't generate warnings at compile time.
This check may warn incorrectly on cases like:
.. code-block:: c++
const char* SupportedFormat[] = {
"Error %s",
"Code " PRIu64, // May warn here.
"Warning %s",
};
Options
-------
.. option:: SizeThreshold
An unsigned integer specifying the minimum size of a string literal to be
considered by the check. Default is ``5U``.
.. option:: RatioThreshold
A string specifying the maximum threshold ratio [0, 1.0] of suspicious string
literals to be considered. Default is ``".2"``.
.. option:: MaxConcatenatedTokens
An unsigned integer specifying the maximum number of concatenated tokens.
Default is ``5U``.
.. title:: clang-tidy - bugprone-suspicious-semicolon
bugprone-suspicious-semicolon
=============================
Finds most instances of stray semicolons that unexpectedly alter the meaning of
the code. More specifically, it looks for ``if``, ``while``, ``for`` and
``for-range`` statements whose body is a single semicolon, and then analyzes the
context of the code (e.g. indentation) in an attempt to determine whether that
is intentional.
.. code-block:: c++
if (x < y);
{
x++;
}
Here the body of the ``if`` statement consists of only the semicolon at the end
of the first line, and `x` will be incremented regardless of the condition.
.. code-block:: c++
while ((line = readLine(file)) != NULL);
processLine(line);
As a result of this code, `processLine()` will only be called once, when the
``while`` loop with the empty body exits with `line == NULL`. The indentation of
the code indicates the intention of the programmer.
.. code-block:: c++
if (x >= y);
x -= y;
While the indentation does not imply any nesting, there is simply no valid
reason to have an `if` statement with an empty body (but it can make sense for
a loop). So this check issues a warning for the code above.
To solve the issue remove the stray semicolon or in case the empty body is
intentional, reflect this using code indentation or put the semicolon in a new
line. For example:
.. code-block:: c++
while (readWhitespace());
Token t = readNextToken();
Here the second line is indented in a way that suggests that it is meant to be
the body of the `while` loop - whose body is in fact empty, because of the
semicolon at the end of the first line.
Either remove the indentation from the second line:
.. code-block:: c++
while (readWhitespace());
Token t = readNextToken();
... or move the semicolon from the end of the first line to a new line:
.. code-block:: c++
while (readWhitespace())
;
Token t = readNextToken();
In this case the check will assume that you know what you are doing, and will
not raise a warning.
.. title:: clang-tidy - bugprone-suspicious-string-compare
bugprone-suspicious-string-compare
==================================
Find suspicious usage of runtime string comparison functions.
This check is valid in C and C++.
Checks for calls with implicit comparator and proposed to explicitly add it.
.. code-block:: c++
if (strcmp(...)) // Implicitly compare to zero
if (!strcmp(...)) // Won't warn
if (strcmp(...) != 0) // Won't warn
Checks that compare function results (i,e, ``strcmp``) are compared to valid
constant. The resulting value is
.. code::
< 0 when lower than,
> 0 when greater than,
== 0 when equals.
A common mistake is to compare the result to `1` or `-1`.
.. code-block:: c++
if (strcmp(...) == -1) // Incorrect usage of the returned value.
Additionally, the check warns if the results value is implicitly cast to a
*suspicious* non-integer type. It's happening when the returned value is used in
a wrong context.
.. code-block:: c++
if (strcmp(...) < 0.) // Incorrect usage of the returned value.
Options
-------
.. option:: WarnOnImplicitComparison
When `true`, the check will warn on implicit comparison. `true` by default.
.. option:: WarnOnLogicalNotComparison
When `true`, the check will warn on logical not comparison. `false` by default.
.. option:: StringCompareLikeFunctions
A string specifying the comma-separated names of the extra string comparison
functions. Default is an empty string.
The check will detect the following string comparison functions:
`__builtin_memcmp`, `__builtin_strcasecmp`, `__builtin_strcmp`,
`__builtin_strncasecmp`, `__builtin_strncmp`, `_mbscmp`, `_mbscmp_l`,
`_mbsicmp`, `_mbsicmp_l`, `_mbsnbcmp`, `_mbsnbcmp_l`, `_mbsnbicmp`,
`_mbsnbicmp_l`, `_mbsncmp`, `_mbsncmp_l`, `_mbsnicmp`, `_mbsnicmp_l`,
`_memicmp`, `_memicmp_l`, `_stricmp`, `_stricmp_l`, `_strnicmp`,
`_strnicmp_l`, `_wcsicmp`, `_wcsicmp_l`, `_wcsnicmp`, `_wcsnicmp_l`,
`lstrcmp`, `lstrcmpi`, `memcmp`, `memicmp`, `strcasecmp`, `strcmp`,
`strcmpi`, `stricmp`, `strncasecmp`, `strncmp`, `strnicmp`, `wcscasecmp`,
`wcscmp`, `wcsicmp`, `wcsncmp`, `wcsnicmp`, `wmemcmp`.
.. title:: clang-tidy - bugprone-swapped-arguments
bugprone-swapped-arguments
==========================
Finds potentially swapped arguments by looking at implicit conversions.
.. title:: clang-tidy - bugprone-terminating-continue
bugprone-terminating-continue
=============================
Detects ``do while`` loops with a condition always evaluating to false that
have a ``continue`` statement, as this ``continue`` terminates the loop
effectively.
.. code-block:: c++
void f() {
do {
// some code
continue; // terminating continue
// some other code
} while(false);
.. title:: clang-tidy - bugprone-throw-keyword-missing
bugprone-throw-keyword-missing
==============================
Warns about a potentially missing ``throw`` keyword. If a temporary object is created, but the
object's type derives from (or is the same as) a class that has 'EXCEPTION', 'Exception' or
'exception' in its name, we can assume that the programmer's intention was to throw that object.
Example:
.. code-block:: c++
void f(int i) {
if (i < 0) {
// Exception is created but is not thrown.
std::runtime_error("Unexpected argument");
}
}
.. title:: clang-tidy - bugprone-too-small-loop-variable
bugprone-too-small-loop-variable
================================
Detects those ``for`` loops that have a loop variable with a "too small" type
which means this type can't represent all values which are part of the
iteration range.
.. code-block:: c++
int main() {
long size = 294967296l;
for (short i = 0; i < size; ++i) {}
}
This ``for`` loop is an infinite loop because the ``short`` type can't represent
all values in the ``[0..size]`` interval.
In a real use case size means a container's size which depends on the user input.
.. code-block:: c++
int doSomething(const std::vector& items) {
for (short i = 0; i < items.size(); ++i) {}
}
This algorithm works for small amount of objects, but will lead to freeze for a
a larger user input.
.. option:: MagnitudeBitsUpperLimit
Upper limit for the magnitude bits of the loop variable. If it's set the check
filters out those catches in which the loop variable's type has more magnitude
bits as the specified upper limit. The default value is 16.
For example, if the user sets this option to 31 (bits), then a 32-bit ``unsigend int``
is ignored by the check, however a 32-bit ``int`` is not (A 32-bit ``signed int``
has 31 magnitude bits).
.. code-block:: c++
int main() {
long size = 294967296l;
for (unsigned i = 0; i < size; ++i) {} // no warning with MagnitudeBitsUpperLimit = 31 on a system where unsigned is 32-bit
for (int i = 0; i < size; ++i) {} // warning with MagnitudeBitsUpperLimit = 31 on a system where int is 32-bit
}
.. title:: clang-tidy - bugprone-undefined-memory-manipulation
bugprone-undefined-memory-manipulation
======================================
Finds calls of memory manipulation functions ``memset()``, ``memcpy()`` and
``memmove()`` on not TriviallyCopyable objects resulting in undefined behavior.
.. title:: clang-tidy - bugprone-undelegated-constructor
bugprone-undelegated-constructor
================================
Finds creation of temporary objects in constructors that look like a
function call to another constructor of the same class.
The user most likely meant to use a delegating constructor or base class
initializer.
.. title:: clang-tidy - bugprone-unhandled-exception-at-new
bugprone-unhandled-exception-at-new
===================================
Finds calls to ``new`` with missing exception handler for ``std::bad_alloc``.
.. code-block:: c++
int *f() noexcept {
int *p = new int[1000];
// ...
return p;
}
Calls to ``new`` can throw exceptions of type ``std::bad_alloc`` that should
be handled by the code. Alternatively, the nonthrowing form of ``new`` can be
used. The check verifies that the exception is handled in the function
that calls ``new``, unless a nonthrowing version is used or the exception
is allowed to propagate out of the function (exception handler is checked for
types ``std::bad_alloc``, ``std::exception``, and catch-all handler).
The check assumes that any user-defined ``operator new`` is either
``noexcept`` or may throw an exception of type ``std::bad_alloc`` (or derived
from it). Other exception types or exceptions occuring in the objects's
constructor are not taken into account.
.. title:: clang-tidy - bugprone-unhandled-self-assignment
bugprone-unhandled-self-assignment
==================================
`cert-oop54-cpp` redirects here as an alias for this check. For the CERT alias,
the `WarnOnlyIfThisHasSuspiciousField` option is set to `false`.
Finds user-defined copy assignment operators which do not protect the code
against self-assignment either by checking self-assignment explicitly or
using the copy-and-swap or the copy-and-move method.
By default, this check searches only those classes which have any pointer or C array field
to avoid false positives. In case of a pointer or a C array, it's likely that self-copy
assignment breaks the object if the copy assignment operator was not written with care.
See also:
`OOP54-CPP. Gracefully handle self-copy assignment
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP54-CPP.+Gracefully+handle+self-copy+assignment>`_
A copy assignment operator must prevent that self-copy assignment ruins the
object state. A typical use case is when the class has a pointer field
and the copy assignment operator first releases the pointed object and
then tries to assign it:
.. code-block:: c++
class T {
int* p;
public:
T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
~T() { delete p; }
// ...
T& operator=(const T &rhs) {
delete p;
p = new int(*rhs.p);
return *this;
}
};
There are two common C++ patterns to avoid this problem. The first is
the self-assignment check:
.. code-block:: c++
class T {
int* p;
public:
T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
~T() { delete p; }
// ...
T& operator=(const T &rhs) {
if(this == &rhs)
return *this;
delete p;
p = new int(*rhs.p);
return *this;
}
};
The second one is the copy-and-swap method when we create a temporary copy
(using the copy constructor) and then swap this temporary object with ``this``:
.. code-block:: c++
class T {
int* p;
public:
T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
~T() { delete p; }
// ...
void swap(T &rhs) {
using std::swap;
swap(p, rhs.p);
}
T& operator=(const T &rhs) {
T(rhs).swap(*this);
return *this;
}
};
There is a third pattern which is less common. Let's call it the copy-and-move method
when we create a temporary copy (using the copy constructor) and then move this
temporary object into ``this`` (needs a move assignment operator):
.. code-block:: c++
class T {
int* p;
public:
T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
~T() { delete p; }
// ...
T& operator=(const T &rhs) {
T t = rhs;
*this = std::move(t);
return *this;
}
T& operator=(T &&rhs) {
p = rhs.p;
rhs.p = nullptr;
return *this;
}
};
.. option:: WarnOnlyIfThisHasSuspiciousField
When `true`, the check will warn only if the container class of the copy assignment operator
has any suspicious fields (pointer or C array). This option is set to `true` by default.
.. title:: clang-tidy - bugprone-unused-raii
bugprone-unused-raii
====================
Finds temporaries that look like RAII objects.
The canonical example for this is a scoped lock.
.. code-block:: c++
{
scoped_lock(&global_mutex);
critical_section();
}
The destructor of the scoped_lock is called before the ``critical_section`` is
entered, leaving it unprotected.
We apply a number of heuristics to reduce the false positive count of this
check:
- Ignore code expanded from macros. Testing frameworks make heavy use of this.
- Ignore types with trivial destructors. They are very unlikely to be RAII
objects and there's no difference when they are deleted.
- Ignore objects at the end of a compound statement (doesn't change behavior).
- Ignore objects returned from a call.
.. title:: clang-tidy - bugprone-unused-return-value
bugprone-unused-return-value
============================
Warns on unused function return values. The checked functions can be configured.
Options
-------
.. option:: CheckedFunctions
Semicolon-separated list of functions to check. Defaults to
``::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique;::std::unique_ptr::release;::std::basic_string::empty;::std::vector::empty``.
This means that the calls to following functions are checked by default:
- ``std::async()``. Not using the return value makes the call synchronous.
- ``std::launder()``. Not using the return value usually means that the
function interface was misunderstood by the programmer. Only the returned
pointer is "laundered", not the argument.
- ``std::remove()``, ``std::remove_if()`` and ``std::unique()``. The returned
iterator indicates the boundary between elements to keep and elements to be
removed. Not using the return value means that the information about which
elements to remove is lost.
- ``std::unique_ptr::release()``. Not using the return value can lead to
resource leaks if the same pointer isn't stored anywhere else. Often,
ignoring the ``release()`` return value indicates that the programmer
confused the function with ``reset()``.
- ``std::basic_string::empty()`` and ``std::vector::empty()``. Not using the
return value often indicates that the programmer confused the function with
``clear()``.
.. title:: clang-tidy - bugprone-use-after-move
bugprone-use-after-move
=======================
Warns if an object is used after it has been moved, for example:
.. code-block:: c++
std::string str = "Hello, world!\n";
std::vector<std::string> messages;
messages.emplace_back(std::move(str));
std::cout << str;
The last line will trigger a warning that ``str`` is used after it has been
moved.
The check does not trigger a warning if the object is reinitialized after the
move and before the use. For example, no warning will be output for this code:
.. code-block:: c++
messages.emplace_back(std::move(str));
str = "Greetings, stranger!\n";
std::cout << str;
Subsections below explain more precisely what exactly the check considers to be
a move, use, and reinitialization.
The check takes control flow into account. A warning is only emitted if the use
can be reached from the move. This means that the following code does not
produce a warning:
.. code-block:: c++
if (condition) {
messages.emplace_back(std::move(str));
} else {
std::cout << str;
}
On the other hand, the following code does produce a warning:
.. code-block:: c++
for (int i = 0; i < 10; ++i) {
std::cout << str;
messages.emplace_back(std::move(str));
}
(The use-after-move happens on the second iteration of the loop.)
In some cases, the check may not be able to detect that two branches are
mutually exclusive. For example (assuming that ``i`` is an int):
.. code-block:: c++
if (i == 1) {
messages.emplace_back(std::move(str));
}
if (i == 2) {
std::cout << str;
}
In this case, the check will erroneously produce a warning, even though it is
not possible for both the move and the use to be executed. More formally, the
analysis is `flow-sensitive but not path-sensitive
<https://en.wikipedia.org/wiki/Data-flow_analysis#Sensitivities>`_.
Silencing erroneous warnings
----------------------------
An erroneous warning can be silenced by reinitializing the object after the
move:
.. code-block:: c++
if (i == 1) {
messages.emplace_back(std::move(str));
str = "";
}
if (i == 2) {
std::cout << str;
}
If you want to avoid the overhead of actually reinitializing the object, you can
create a dummy function that causes the check to assume the object was
reinitialized:
.. code-block:: c++
template <class T>
void IS_INITIALIZED(T&) {}
You can use this as follows:
.. code-block:: c++
if (i == 1) {
messages.emplace_back(std::move(str));
}
if (i == 2) {
IS_INITIALIZED(str);
std::cout << str;
}
The check will not output a warning in this case because passing the object to a
function as a non-const pointer or reference counts as a reinitialization (see section
`Reinitialization`_ below).
Unsequenced moves, uses, and reinitializations
----------------------------------------------
In many cases, C++ does not make any guarantees about the order in which
sub-expressions of a statement are evaluated. This means that in code like the
following, it is not guaranteed whether the use will happen before or after the
move:
.. code-block:: c++
void f(int i, std::vector<int> v);
std::vector<int> v = { 1, 2, 3 };
f(v[1], std::move(v));
In this kind of situation, the check will note that the use and move are
unsequenced.
The check will also take sequencing rules into account when reinitializations
occur in the same statement as moves or uses. A reinitialization is only
considered to reinitialize a variable if it is guaranteed to be evaluated after
the move and before the use.
Move
----
The check currently only considers calls of ``std::move`` on local variables or
function parameters. It does not check moves of member variables or global
variables.
Any call of ``std::move`` on a variable is considered to cause a move of that
variable, even if the result of ``std::move`` is not passed to an rvalue
reference parameter.
This means that the check will flag a use-after-move even on a type that does
not define a move constructor or move assignment operator. This is intentional.
Developers may use ``std::move`` on such a type in the expectation that the type
will add move semantics in the future. If such a ``std::move`` has the potential
to cause a use-after-move, we want to warn about it even if the type does not
implement move semantics yet.
Furthermore, if the result of ``std::move`` *is* passed to an rvalue reference
parameter, this will always be considered to cause a move, even if the function
that consumes this parameter does not move from it, or if it does so only
conditionally. For example, in the following situation, the check will assume
that a move always takes place:
.. code-block:: c++
std::vector<std::string> messages;
void f(std::string &&str) {
// Only remember the message if it isn't empty.
if (!str.empty()) {
messages.emplace_back(std::move(str));
}
}
std::string str = "";
f(std::move(str));
The check will assume that the last line causes a move, even though, in this
particular case, it does not. Again, this is intentional.
There is one special case: A call to ``std::move`` inside a ``try_emplace`` call
is conservatively assumed not to move. This is to avoid spurious warnings, as
the check has no way to reason about the ``bool`` returned by ``try_emplace``.
When analyzing the order in which moves, uses and reinitializations happen (see
section `Unsequenced moves, uses, and reinitializations`_), the move is assumed
to occur in whichever function the result of the ``std::move`` is passed to.
Use
---
Any occurrence of the moved variable that is not a reinitialization (see below)
is considered to be a use.
An exception to this are objects of type ``std::unique_ptr``,
``std::shared_ptr`` and ``std::weak_ptr``, which have defined move behavior
(objects of these classes are guaranteed to be empty after they have been moved
from). Therefore, an object of these classes will only be considered to be used
if it is dereferenced, i.e. if ``operator*``, ``operator->`` or ``operator[]``
(in the case of ``std::unique_ptr<T []>``) is called on it.
If multiple uses occur after a move, only the first of these is flagged.
Reinitialization
----------------
The check considers a variable to be reinitialized in the following cases:
- The variable occurs on the left-hand side of an assignment.
- The variable is passed to a function as a non-const pointer or non-const
lvalue reference. (It is assumed that the variable may be an out-parameter
for the function.)
- ``clear()`` or ``assign()`` is called on the variable and the variable is of
one of the standard container types ``basic_string``, ``vector``, ``deque``,
``forward_list``, ``list``, ``set``, ``map``, ``multiset``, ``multimap``,
``unordered_set``, ``unordered_map``, ``unordered_multiset``,
``unordered_multimap``.
- ``reset()`` is called on the variable and the variable is of type
``std::unique_ptr``, ``std::shared_ptr`` or ``std::weak_ptr``.
- A member function marked with the ``[[clang::reinitializes]]`` attribute is
called on the variable.
If the variable in question is a struct and an individual member variable of
that struct is written to, the check does not consider this to be a
reinitialization -- even if, eventually, all member variables of the struct are
written to. For example:
.. code-block:: c++
struct S {
std::string str;
int i;
};
S s = { "Hello, world!\n", 42 };
S s_other = std::move(s);
s.str = "Lorem ipsum";
s.i = 99;
The check will not consider ``s`` to be reinitialized after the last line;
instead, the line that assigns to ``s.str`` will be flagged as a use-after-move.
This is intentional as this pattern of reinitializing a struct is error-prone.
For example, if an additional member variable is added to ``S``, it is easy to
forget to add the reinitialization for this additional member. Instead, it is
safer to assign to the entire struct in one go, and this will also avoid the
use-after-move warning.
.. title:: clang-tidy - bugprone-virtual-near-miss
bugprone-virtual-near-miss
==========================
Warn if a function is a near miss (ie. the name is very similar and the function
signature is the same) to a virtual function from a base class.
Example:
.. code-block:: c++
struct Base {
virtual void func();
};
struct Derived : Base {
virtual funk();
// warning: 'Derived::funk' has a similar name and the same signature as virtual method 'Base::func'; did you mean to override it?
};
.. title:: clang-tidy - cert-con36-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-spuriously-wake-up-functions.html
cert-con36-c
============
The cert-con36-c check is an alias, please see
`bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_
for more information.
.. title:: clang-tidy - cert-con54-cpp
.. meta::
:http-equiv=refresh: 5;URL=bugprone-spuriously-wake-up-functions.html
cert-con54-cpp
==============
The cert-con54-cpp check is an alias, please see
`bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_
for more information.
.. title:: clang-tidy - cert-dcl03-c
.. meta::
:http-equiv=refresh: 5;URL=misc-static-assert.html
cert-dcl03-c
============
The cert-dcl03-c check is an alias, please see
`misc-static-assert <misc-static-assert.html>`_ for more information.
.. title:: clang-tidy - cert-dcl16-c
.. meta::
:http-equiv=refresh: 5;URL=readability-uppercase-literal-suffix.html
cert-dcl16-c
============
The cert-dcl16-c check is an alias, please see
`readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_ for more information.
.. title:: clang-tidy - cert-dcl21-cpp
cert-dcl21-cpp
==============
This check flags postfix ``operator++`` and ``operator--`` declarations
if the return type is not a const object. This also warns if the return type
is a reference type.
The object returned by a postfix increment or decrement operator is supposed
to be a snapshot of the object's value prior to modification. With such an
implementation, any modifications made to the resulting object from calling
operator++(int) would be modifying a temporary object. Thus, such an
implementation of a postfix increment or decrement operator should instead
return a const object, prohibiting accidental mutation of a temporary object.
Similarly, it is unexpected for the postfix operator to return a reference to
its previous state, and any subsequent modifications would be operating on a
stale object.
This check corresponds to the CERT C++ Coding Standard recommendation
DCL21-CPP. Overloaded postfix increment and decrement operators should return a
const object. However, all of the CERT recommendations have been removed from
public view, and so their justification for the behavior of this check requires
an account on their wiki to view... title:: clang-tidy - cert-dcl37-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-reserved-identifier.html
cert-dcl37-c
============
The cert-dcl37-c check is an alias, please see
`bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_ for more
information.
.. title:: clang-tidy - cert-dcl50-cpp
cert-dcl50-cpp
==============
This check flags all function definitions (but not declarations) of C-style
variadic functions.
This check corresponds to the CERT C++ Coding Standard rule
`DCL50-CPP. Do not define a C-style variadic function
<https://www.securecoding.cert.org/confluence/display/cplusplus/DCL50-CPP.+Do+not+define+a+C-style+variadic+function>`_.
.. title:: clang-tidy - cert-dcl51-cpp
.. meta::
:http-equiv=refresh: 5;URL=bugprone-reserved-identifier.html
cert-dcl51-cpp
==============
The cert-dcl51-cpp check is an alias, please see
`bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_ for more
information.
.. title:: clang-tidy - cert-dcl54-cpp
.. meta::
:http-equiv=refresh: 5;URL=misc-new-delete-overloads.html
cert-dcl54-cpp
==============
The cert-dcl54-cpp check is an alias, please see
`misc-new-delete-overloads <misc-new-delete-overloads.html>`_ for more
information.
.. title:: clang-tidy - cert-dcl58-cpp
cert-dcl58-cpp
==============
Modification of the ``std`` or ``posix`` namespace can result in undefined
behavior.
This check warns for such modifications.
Examples:
.. code-block:: c++
namespace std {
int x; // May cause undefined behavior.
}
This check corresponds to the CERT C++ Coding Standard rule
`DCL58-CPP. Do not modify the standard namespaces
<https://www.securecoding.cert.org/confluence/display/cplusplus/DCL58-CPP.+Do+not+modify+the+standard+namespaces>`_.
.. title:: clang-tidy - cert-dcl59-cpp
.. meta::
:http-equiv=refresh: 5;URL=google-build-namespaces.html
cert-dcl59-cpp
==============
The cert-dcl59-cpp check is an alias, please see
`google-build-namespaces <google-build-namespaces.html>`_ for more information.
.. title:: clang-tidy - cert-env33-c
cert-env33-c
============
This check flags calls to ``system()``, ``popen()``, and ``_popen()``, which
execute a command processor. It does not flag calls to ``system()`` with a null
pointer argument, as such a call checks for the presence of a command processor
but does not actually attempt to execute a command.
This check corresponds to the CERT C Coding Standard rule
`ENV33-C. Do not call system()
<https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=2130132>`_.
.. title:: clang-tidy - cert-err09-cpp
.. meta::
:http-equiv=refresh: 5;URL=misc-throw-by-value-catch-by-reference.html
cert-err09-cpp
==============
The cert-err09-cpp check is an alias, please see
`misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_
for more information.
This check corresponds to the CERT C++ Coding Standard recommendation
ERR09-CPP. Throw anonymous temporaries. However, all of the CERT recommendations
have been removed from public view, and so their justification for the behavior
of this check requires an account on their wiki to view... title:: clang-tidy - cert-err34-c
cert-err34-c
============
This check flags calls to string-to-number conversion functions that do not
verify the validity of the conversion, such as ``atoi()`` or ``scanf()``. It
does not flag calls to ``strtol()``, or other, related conversion functions that
do perform better error checking.
.. code-block:: c
#include <stdlib.h>
void func(const char *buff) {
int si;
if (buff) {
si = atoi(buff); /* 'atoi' used to convert a string to an integer, but function will
not report conversion errors; consider using 'strtol' instead. */
} else {
/* Handle error */
}
}
This check corresponds to the CERT C Coding Standard rule
`ERR34-C. Detect errors when converting a string to a number
<https://www.securecoding.cert.org/confluence/display/c/ERR34-C.+Detect+errors+when+converting+a+string+to+a+number>`_.
.. title:: clang-tidy - cert-err52-cpp
cert-err52-cpp
==============
This check flags all call expressions involving ``setjmp()`` and ``longjmp()``.
This check corresponds to the CERT C++ Coding Standard rule
`ERR52-CPP. Do not use setjmp() or longjmp()
<https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=1834>`_.
.. title:: clang-tidy - cert-err58-cpp
cert-err58-cpp
==============
This check flags all ``static`` or ``thread_local`` variable declarations where
the initializer for the object may throw an exception.
This check corresponds to the CERT C++ Coding Standard rule
`ERR58-CPP. Handle all exceptions thrown before main() begins executing
<https://www.securecoding.cert.org/confluence/display/cplusplus/ERR58-CPP.+Handle+all+exceptions+thrown+before+main%28%29+begins+executing>`_.
.. title:: clang-tidy - cert-err60-cpp
cert-err60-cpp
==============
This check flags all throw expressions where the exception object is not nothrow
copy constructible.
This check corresponds to the CERT C++ Coding Standard rule
`ERR60-CPP. Exception objects must be nothrow copy constructible
<https://www.securecoding.cert.org/confluence/display/cplusplus/ERR60-CPP.+Exception+objects+must+be+nothrow+copy+constructible>`_.
.. title:: clang-tidy - cert-err61-cpp
.. meta::
:http-equiv=refresh: 5;URL=misc-throw-by-value-catch-by-reference.html
cert-err61-cpp
==============
The cert-err61-cpp check is an alias, please see
`misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_
for more information.
.. title:: clang-tidy - cert-fio38-c
.. meta::
:http-equiv=refresh: 5;URL=misc-non-copyable-objects.html
cert-fio38-c
============
The cert-fio38-c check is an alias, please see
`misc-non-copyable-objects <misc-non-copyable-objects.html>`_ for more
information.
.. title:: clang-tidy - cert-flp30-c
cert-flp30-c
============
This check flags ``for`` loops where the induction expression has a
floating-point type.
This check corresponds to the CERT C Coding Standard rule
`FLP30-C. Do not use floating-point variables as loop counters
<https://www.securecoding.cert.org/confluence/display/c/FLP30-C.+Do+not+use+floating-point+variables+as+loop+counters>`_.
.. title:: clang-tidy - cert-mem57-cpp
cert-mem57-cpp
==============
This check flags uses of default ``operator new`` where the type has extended
alignment (an alignment greater than the fundamental alignment). (The default
``operator new`` is guaranteed to provide the correct alignment if the
requested alignment is less or equal to the fundamental alignment).
Only cases are detected (by design) where the ``operator new`` is not
user-defined and is not a placement new (the reason is that in these cases we
assume that the user provided the correct memory allocation).
This check corresponds to the CERT C++ Coding Standard rule
`MEM57-CPP. Avoid using default operator new for over-aligned types
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/MEM57-CPP.+Avoid+using+default+operator+new+for+over-aligned+types>`_.
.. title:: clang-tidy - cert-msc30-c
.. meta::
:http-equiv=refresh: 5;URL=cert-msc50-cpp.html
cert-msc30-c
============
The cert-msc30-c check is an alias, please see
`cert-msc50-cpp <cert-msc50-cpp.html>`_ for more information.
.. title:: clang-tidy - cert-msc32-c
.. meta::
:http-equiv=refresh: 5;URL=cert-msc51-cpp.html
cert-msc32-c
============
The cert-msc32-c check is an alias, please see
`cert-msc51-cpp <cert-msc51-cpp.html>`_ for more information.
.. title:: clang-tidy - cert-msc50-cpp
cert-msc50-cpp
==============
Pseudorandom number generators use mathematical algorithms to produce a sequence
of numbers with good statistical properties, but the numbers produced are not
genuinely random. The ``std::rand()`` function takes a seed (number), runs a
mathematical operation on it and returns the result. By manipulating the seed
the result can be predictable. This check warns for the usage of
``std::rand()``.
.. title:: clang-tidy - cert-msc51-cpp
cert-msc51-cpp
==============
This check flags all pseudo-random number engines, engine adaptor
instantiations and ``srand()`` when initialized or seeded with default argument,
constant expression or any user-configurable type. Pseudo-random number
engines seeded with a predictable value may cause vulnerabilities e.g. in
security protocols.
This is a CERT security rule, see
`MSC51-CPP. Ensure your random number generator is properly seeded
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/MSC51-CPP.+Ensure+your+random+number+generator+is+properly+seeded>`_ and
`MSC32-C. Properly seed pseudorandom number generators
<https://wiki.sei.cmu.edu/confluence/display/c/MSC32-C.+Properly+seed+pseudorandom+number+generators>`_.
Examples:
.. code-block:: c++
void foo() {
std::mt19937 engine1; // Diagnose, always generate the same sequence
std::mt19937 engine2(1); // Diagnose
engine1.seed(); // Diagnose
engine2.seed(1); // Diagnose
std::time_t t;
engine1.seed(std::time(&t)); // Diagnose, system time might be controlled by user
int x = atoi(argv[1]);
std::mt19937 engine3(x); // Will not warn
}
Options
-------
.. option:: DisallowedSeedTypes
A comma-separated list of the type names which are disallowed.
Default values are ``time_t``, ``std::time_t``.
.. title:: clang-tidy - cert-oop11-cpp
.. meta::
:http-equiv=refresh: 5;URL=performance-move-constructor-init.html
cert-oop11-cpp
==============
The cert-oop11-cpp check is an alias, please see
`performance-move-constructor-init <performance-move-constructor-init.html>`_
for more information.
This check corresponds to the CERT C++ Coding Standard recommendation
OOP11-CPP. Do not copy-initialize members or base classes from a move
constructor. However, all of the CERT recommendations have been removed from
public view, and so their justification for the behavior of this check requires
an account on their wiki to view... title:: clang-tidy - cert-oop54-cpp
.. meta::
:http-equiv=refresh: 5;URL=bugprone-unhandled-self-assignment.html
cert-oop54-cpp
==============
The cert-oop54-cpp check is an alias, please see
`bugprone-unhandled-self-assignment <bugprone-unhandled-self-assignment.html>`_
for more information.
.. title:: clang-tidy - cert-oop57-cpp
cert-oop57-cpp
==============
Flags use of the `C` standard library functions ``memset``, ``memcpy`` and
``memcmp`` and similar derivatives on non-trivial types.
Options
-------
.. option:: MemSetNames
Specify extra functions to flag that act similarily to ``memset``.
Specify names in a semicolon delimited list.
Default is an empty string.
The check will detect the following functions:
`memset`, `std::memset`.
.. option:: MemCpyNames
Specify extra functions to flag that act similarily to ``memcpy``.
Specify names in a semicolon delimited list.
Default is an empty string.
The check will detect the following functions:
`std::memcpy`, `memcpy`, `std::memmove`, `memmove`, `std::strcpy`,
`strcpy`, `memccpy`, `stpncpy`, `strncpy`.
.. option:: MemCmpNames
Specify extra functions to flag that act similarily to ``memcmp``.
Specify names in a semicolon delimited list.
Default is an empty string.
The check will detect the following functions:
`std::memcmp`, `memcmp`, `std::strcmp`, `strcmp`, `strncmp`.
This check corresponds to the CERT C++ Coding Standard rule
`OOP57-CPP. Prefer special member functions and overloaded operators to C
Standard Library functions
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP57-CPP.+Prefer+special+member+functions+and+overloaded+operators+to+C+Standard+Library+functions>`_.
.. title:: clang-tidy - cert-mutating-copy
cert-oop58-cpp
==============
Finds assignments to the copied object and its direct or indirect members
in copy constructors and copy assignment operators.
This check corresponds to the CERT C Coding Standard rule
`OOP58-CPP. Copy operations must not mutate the source object
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP58-CPP.+Copy+operations+must+not+mutate+the+source+object>`_.
.. title:: clang-tidy - cert-pos44-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-bad-signal-to-kill-thread.html
cert-pos44-c
============
The cert-pos44-c check is an alias, please see
`bugprone-bad-signal-to-kill-thread <bugprone-bad-signal-to-kill-thread.html>`_ for more information.
.. title:: clang-tidy - cert-pos47-c
.. meta::
:http-equiv=refresh: 5;URL=concurrency-thread-canceltype-asynchronous.html
cert-pos47-c
============
The cert-pos47-c check is an alias, please see
`concurrency-thread-canceltype-asynchronous <concurrency-thread-canceltype-asynchronous.html>`_ for more information.
.. title:: clang-tidy - cert-sig30-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-signal-handler.html
cert-sig30-c
============
The cert-sig30-c check is an alias, please see
`bugprone-signal-handler <bugprone-signal-handler.html>`_
for more information.
.. title:: clang-tidy - cert-str34-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-signed-char-misuse.html
cert-str34-c
============
The cert-str34-c check is an alias, please see
`bugprone-signed-char-misuse <bugprone-signed-char-misuse.html>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.CallAndMessage
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-callandmessage
clang-analyzer-core.CallAndMessage
==================================
The clang-analyzer-core.CallAndMessage check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-callandmessage>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.DivideZero
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-dividezero
clang-analyzer-core.DivideZero
==============================
The clang-analyzer-core.DivideZero check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-dividezero>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.DynamicTypePropagation
clang-analyzer-core.DynamicTypePropagation
==========================================
Generate dynamic type information
.. title:: clang-tidy - clang-analyzer-core.NonNullParamChecker
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-nonnullparamchecker
clang-analyzer-core.NonNullParamChecker
=======================================
The clang-analyzer-core.NonNullParamChecker check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-nonnullparamchecker>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.NullDereference
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-nulldereference
clang-analyzer-core.NullDereference
===================================
The clang-analyzer-core.NullDereference check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-nulldereference>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.StackAddressEscape
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-stackaddressescape
clang-analyzer-core.StackAddressEscape
======================================
The clang-analyzer-core.StackAddressEscape check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-stackaddressescape>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.UndefinedBinaryOperatorResult
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-undefinedbinaryoperatorresult
clang-analyzer-core.UndefinedBinaryOperatorResult
=================================================
The clang-analyzer-core.UndefinedBinaryOperatorResult check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-undefinedbinaryoperatorresult>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.uninitialized.ArraySubscript
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-arraysubscript
clang-analyzer-core.uninitialized.ArraySubscript
================================================
The clang-analyzer-core.uninitialized.ArraySubscript check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-arraysubscript>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.uninitialized.Assign
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-assign
clang-analyzer-core.uninitialized.Assign
========================================
The clang-analyzer-core.uninitialized.Assign check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-assign>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.uninitialized.Branch
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-branch
clang-analyzer-core.uninitialized.Branch
========================================
The clang-analyzer-core.uninitialized.Branch check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-branch>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.uninitialized.CapturedBlockVariable
clang-analyzer-core.uninitialized.CapturedBlockVariable
=======================================================
Check for blocks that capture uninitialized values
.. title:: clang-tidy - clang-analyzer-core.uninitialized.UndefReturn
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-undefreturn
clang-analyzer-core.uninitialized.UndefReturn
=============================================
The clang-analyzer-core.uninitialized.UndefReturn check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-undefreturn>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.VLASize
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-vlasize
clang-analyzer-core.VLASize
===========================
The clang-analyzer-core.VLASize check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-vlasize>`_
for more information.
.. title:: clang-tidy - clang-analyzer-cplusplus.InnerPointer
clang-analyzer-cplusplus.InnerPointer
=====================================
Check for inner pointers of C++ containers used after re/deallocation
.. title:: clang-tidy - clang-analyzer-cplusplus.Move
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-move
clang-analyzer-cplusplus.Move
=============================
The clang-analyzer-cplusplus.Move check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-move>`_
for more information.
.. title:: clang-tidy - clang-analyzer-cplusplus.NewDelete
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-newdelete
clang-analyzer-cplusplus.NewDelete
==================================
The clang-analyzer-cplusplus.NewDelete check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-newdelete>`_
for more information.
.. title:: clang-tidy - clang-analyzer-cplusplus.NewDeleteLeaks
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-newdeleteleaks
clang-analyzer-cplusplus.NewDeleteLeaks
=======================================
The clang-analyzer-cplusplus.NewDeleteLeaks check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-newdeleteleaks>`_
for more information.
.. title:: clang-tidy - clang-analyzer-deadcode.DeadStores
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#deadcode-deadstores
clang-analyzer-deadcode.DeadStores
==================================
The clang-analyzer-deadcode.DeadStores check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#deadcode-deadstores>`_
for more information.
.. title:: clang-tidy - clang-analyzer-nullability.NullableDereferenced
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullabledereferenced
clang-analyzer-nullability.NullableDereferenced
===============================================
The clang-analyzer-nullability.NullableDereferenced check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullabledereferenced>`_
for more information.
.. title:: clang-tidy - clang-analyzer-nullability.NullablePassedToNonnull
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullablepassedtononnull
clang-analyzer-nullability.NullablePassedToNonnull
==================================================
The clang-analyzer-nullability.NullablePassedToNonnull check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullablepassedtononnull>`_
for more information.
.. title:: clang-tidy - clang-analyzer-nullability.NullableReturnedFromNonnull
clang-analyzer-nullability.NullableReturnedFromNonnull
======================================================
Warns when a nullable pointer is returned from a function that has _Nonnull return type.
.. title:: clang-tidy - clang-analyzer-nullability.NullPassedToNonnull
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullpassedtononnull
clang-analyzer-nullability.NullPassedToNonnull
==============================================
The clang-analyzer-nullability.NullPassedToNonnull check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullpassedtononnull>`_
for more information.
.. title:: clang-tidy - clang-analyzer-nullability.NullReturnedFromNonnull
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullreturnedfromnonnull
clang-analyzer-nullability.NullReturnedFromNonnull
==================================================
The clang-analyzer-nullability.NullReturnedFromNonnull check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullreturnedfromnonnull>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.cplusplus.UninitializedObject
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-cplusplus-uninitializedobject
clang-analyzer-optin.cplusplus.UninitializedObject
==================================================
The clang-analyzer-optin.cplusplus.UninitializedObject check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-cplusplus-uninitializedobject>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.cplusplus.VirtualCall
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-cplusplus-virtualcall
clang-analyzer-optin.cplusplus.VirtualCall
==========================================
The clang-analyzer-optin.cplusplus.VirtualCall check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-cplusplus-virtualcall>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.mpi.MPI-Checker
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-mpi-mpi-checker
clang-analyzer-optin.mpi.MPI-Checker
====================================
The clang-analyzer-optin.mpi.MPI-Checker check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-mpi-mpi-checker>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-osx-cocoa-localizability-emptylocalizationcontextchecker
clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker
=============================================================================
The clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-osx-cocoa-localizability-emptylocalizationcontextchecker>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-osx-cocoa-localizability-nonlocalizedstringchecker
clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker
=======================================================================
The clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-osx-cocoa-localizability-nonlocalizedstringchecker>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.osx.OSObjectCStyleCast
clang-analyzer-optin.osx.OSObjectCStyleCast
===========================================
Checker for C-style casts of OSObjects
.. title:: clang-tidy - clang-analyzer-optin.performance.GCDAntipattern
clang-analyzer-optin.performance.GCDAntipattern
===============================================
Check for performance anti-patterns when using Grand Central Dispatch
.. title:: clang-tidy - clang-analyzer-optin.performance.Padding
clang-analyzer-optin.performance.Padding
========================================
Check for excessively padded structs.
.. title:: clang-tidy - clang-analyzer-optin.portability.UnixAPI
clang-analyzer-optin.portability.UnixAPI
========================================
Finds implementation-defined behavior in UNIX/Posix functions
.. title:: clang-tidy - clang-analyzer-osx.API
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-api
clang-analyzer-osx.API
======================
The clang-analyzer-osx.API check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-api>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.AtSync
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-atsync
clang-analyzer-osx.cocoa.AtSync
===============================
The clang-analyzer-osx.cocoa.AtSync check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-atsync>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.AutoreleaseWrite
clang-analyzer-osx.cocoa.AutoreleaseWrite
=========================================
Warn about potentially crashing writes to autoreleasing objects from different autoreleasing pools in Objective-C
.. title:: clang-tidy - clang-analyzer-osx.cocoa.ClassRelease
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-classrelease
clang-analyzer-osx.cocoa.ClassRelease
=====================================
The clang-analyzer-osx.cocoa.ClassRelease check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-classrelease>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.Dealloc
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-dealloc
clang-analyzer-osx.cocoa.Dealloc
================================
The clang-analyzer-osx.cocoa.Dealloc check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-dealloc>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.IncompatibleMethodTypes
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-incompatiblemethodtypes
clang-analyzer-osx.cocoa.IncompatibleMethodTypes
================================================
The clang-analyzer-osx.cocoa.IncompatibleMethodTypes check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-incompatiblemethodtypes>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.Loops
clang-analyzer-osx.cocoa.Loops
==============================
Improved modeling of loops using Cocoa collection types
.. title:: clang-tidy - clang-analyzer-osx.cocoa.MissingSuperCall
clang-analyzer-osx.cocoa.MissingSuperCall
=========================================
Warn about Objective-C methods that lack a necessary call to super
.. title:: clang-tidy - clang-analyzer-osx.cocoa.NilArg
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nilarg
clang-analyzer-osx.cocoa.NilArg
===============================
The clang-analyzer-osx.cocoa.NilArg check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nilarg>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.NonNilReturnValue
clang-analyzer-osx.cocoa.NonNilReturnValue
==========================================
Model the APIs that are guaranteed to return a non-nil value
.. title:: clang-tidy - clang-analyzer-osx.cocoa.NSAutoreleasePool
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nsautoreleasepool
clang-analyzer-osx.cocoa.NSAutoreleasePool
==========================================
The clang-analyzer-osx.cocoa.NSAutoreleasePool check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nsautoreleasepool>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.NSError
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nserror
clang-analyzer-osx.cocoa.NSError
================================
The clang-analyzer-osx.cocoa.NSError check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nserror>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.ObjCGenerics
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-objcgenerics
clang-analyzer-osx.cocoa.ObjCGenerics
=====================================
The clang-analyzer-osx.cocoa.ObjCGenerics check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-objcgenerics>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.RetainCount
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-retaincount
clang-analyzer-osx.cocoa.RetainCount
====================================
The clang-analyzer-osx.cocoa.RetainCount check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-retaincount>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak
clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak
===============================================
Check for leaked memory in autorelease pools that will never be drained
.. title:: clang-tidy - clang-analyzer-osx.cocoa.SelfInit
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-selfinit
clang-analyzer-osx.cocoa.SelfInit
=================================
The clang-analyzer-osx.cocoa.SelfInit check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-selfinit>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.SuperDealloc
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-superdealloc
clang-analyzer-osx.cocoa.SuperDealloc
=====================================
The clang-analyzer-osx.cocoa.SuperDealloc check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-superdealloc>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.UnusedIvars
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-unusedivars
clang-analyzer-osx.cocoa.UnusedIvars
====================================
The clang-analyzer-osx.cocoa.UnusedIvars check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-unusedivars>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.VariadicMethodTypes
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-variadicmethodtypes
clang-analyzer-osx.cocoa.VariadicMethodTypes
============================================
The clang-analyzer-osx.cocoa.VariadicMethodTypes check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-variadicmethodtypes>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.CFError
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cferror
clang-analyzer-osx.coreFoundation.CFError
=========================================
The clang-analyzer-osx.coreFoundation.CFError check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cferror>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.CFNumber
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cfnumber
clang-analyzer-osx.coreFoundation.CFNumber
==========================================
The clang-analyzer-osx.coreFoundation.CFNumber check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cfnumber>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.CFRetainRelease
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cfretainrelease
clang-analyzer-osx.coreFoundation.CFRetainRelease
=================================================
The clang-analyzer-osx.coreFoundation.CFRetainRelease check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cfretainrelease>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.containers.OutOfBounds
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-containers-outofbounds
clang-analyzer-osx.coreFoundation.containers.OutOfBounds
========================================================
The clang-analyzer-osx.coreFoundation.containers.OutOfBounds check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-containers-outofbounds>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.containers.PointerSizedValues
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-containers-pointersizedvalues
clang-analyzer-osx.coreFoundation.containers.PointerSizedValues
===============================================================
The clang-analyzer-osx.coreFoundation.containers.PointerSizedValues check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-containers-pointersizedvalues>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.MIG
clang-analyzer-osx.MIG
======================
Find violations of the Mach Interface Generator calling convention
.. title:: clang-tidy - clang-analyzer-osx.NumberObjectConversion
clang-analyzer-osx.NumberObjectConversion
=========================================
Check for erroneous conversions of objects representing numbers into numbers
.. title:: clang-tidy - clang-analyzer-osx.ObjCProperty
clang-analyzer-osx.ObjCProperty
===============================
Check for proper uses of Objective-C properties
.. title:: clang-tidy - clang-analyzer-osx.OSObjectRetainCount
clang-analyzer-osx.OSObjectRetainCount
======================================
Check for leaks and improper reference count management for OSObject
.. title:: clang-tidy - clang-analyzer-osx.SecKeychainAPI
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-seckeychainapi
clang-analyzer-osx.SecKeychainAPI
=================================
The clang-analyzer-osx.SecKeychainAPI check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-seckeychainapi>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.FloatLoopCounter
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-floatloopcounter
clang-analyzer-security.FloatLoopCounter
========================================
The clang-analyzer-security.FloatLoopCounter check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-floatloopcounter>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.bcmp
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bcmp
clang-analyzer-security.insecureAPI.bcmp
========================================
The clang-analyzer-security.insecureAPI.bcmp check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bcmp>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.bcopy
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bcopy
clang-analyzer-security.insecureAPI.bcopy
=========================================
The clang-analyzer-security.insecureAPI.bcopy check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bcopy>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.bzero
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bzero
clang-analyzer-security.insecureAPI.bzero
=========================================
The clang-analyzer-security.insecureAPI.bzero check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bzero>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-deprecatedorunsafebufferhandling
clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling
====================================================================
The clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-deprecatedorunsafebufferhandling>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.getpw
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-getpw
clang-analyzer-security.insecureAPI.getpw
=========================================
The clang-analyzer-security.insecureAPI.getpw check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-getpw>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.gets
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-gets
clang-analyzer-security.insecureAPI.gets
========================================
The clang-analyzer-security.insecureAPI.gets check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-gets>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.mkstemp
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-mkstemp
clang-analyzer-security.insecureAPI.mkstemp
===========================================
The clang-analyzer-security.insecureAPI.mkstemp check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-mkstemp>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.mktemp
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-mktemp
clang-analyzer-security.insecureAPI.mktemp
==========================================
The clang-analyzer-security.insecureAPI.mktemp check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-mktemp>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.rand
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-rand
clang-analyzer-security.insecureAPI.rand
========================================
The clang-analyzer-security.insecureAPI.rand check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-rand>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.strcpy
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-strcpy
clang-analyzer-security.insecureAPI.strcpy
==========================================
The clang-analyzer-security.insecureAPI.strcpy check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-strcpy>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.UncheckedReturn
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-uncheckedreturn
clang-analyzer-security.insecureAPI.UncheckedReturn
===================================================
The clang-analyzer-security.insecureAPI.UncheckedReturn check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-uncheckedreturn>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.vfork
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-vfork
clang-analyzer-security.insecureAPI.vfork
=========================================
The clang-analyzer-security.insecureAPI.vfork check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-vfork>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.API
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-api
clang-analyzer-unix.API
=======================
The clang-analyzer-unix.API check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-api>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.cstring.BadSizeArg
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-cstring-badsizearg
clang-analyzer-unix.cstring.BadSizeArg
======================================
The clang-analyzer-unix.cstring.BadSizeArg check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-cstring-badsizearg>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.cstring.NullArg
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-cstring-nullarg
clang-analyzer-unix.cstring.NullArg
===================================
The clang-analyzer-unix.cstring.NullArg check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-cstring-nullarg>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.Malloc
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-malloc
clang-analyzer-unix.Malloc
==========================
The clang-analyzer-unix.Malloc check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-malloc>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.MallocSizeof
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-mallocsizeof
clang-analyzer-unix.MallocSizeof
================================
The clang-analyzer-unix.MallocSizeof check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-mallocsizeof>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.MismatchedDeallocator
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-mismatcheddeallocator
clang-analyzer-unix.MismatchedDeallocator
=========================================
The clang-analyzer-unix.MismatchedDeallocator check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-mismatcheddeallocator>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.Vfork
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-vfork
clang-analyzer-unix.Vfork
=========================
The clang-analyzer-unix.Vfork check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-vfork>`_
for more information.
.. title:: clang-tidy - clang-analyzer-valist.CopyToSelf
clang-analyzer-valist.CopyToSelf
================================
Check for va_lists which are copied onto itself.
.. title:: clang-tidy - clang-analyzer-valist.Uninitialized
clang-analyzer-valist.Uninitialized
===================================
Check for usages of uninitialized (or already released) va_lists.
.. title:: clang-tidy - clang-analyzer-valist.Unterminated
clang-analyzer-valist.Unterminated
==================================
Check for va_lists which are not released by a va_end call.
.. title:: clang-tidy - concurrency-mt-unsafe
concurrency-mt-unsafe
=====================
Checks for some thread-unsafe functions against a black list of
known-to-be-unsafe functions. Usually they access static variables without
synchronization (e.g. gmtime(3)) or utilize signals in a racy way.
The set of functions to check is specified with the `FunctionSet` option.
Note that using some thread-unsafe functions may be still valid in
concurrent programming if only a single thread is used (e.g. setenv(3)),
however, some functions may track a state in global variables which
would be clobbered by subsequent (non-parallel, but concurrent) calls to
a related function. E.g. the following code suffers from unprotected
accesses to a global state:
.. code-block:: c++
// getnetent(3) maintains global state with DB connection, etc.
// If a concurrent green thread calls getnetent(3), the global state is corrupted.
netent = getnetent();
yield();
netent = getnetent();
Examples:
.. code-block:: c++
tm = gmtime(timep); // uses a global buffer
sleep(1); // implementation may use SIGALRM
.. option:: FunctionSet
Specifies which functions in libc should be considered thread-safe,
possible values are `posix`, `glibc`, or `any`.
`posix` means POSIX defined thread-unsafe functions. POSIX.1-2001
in "2.9.1 Thread-Safety" defines that all functions specified in the
standard are thread-safe except a predefined list of thread-unsafe
functions.
Glibc defines some of them as thread-safe (e.g. dirname(3)), but adds
non-POSIX thread-unsafe ones (e.g. getopt_long(3)). Glibc's list is
compiled from GNU web documentation with a search for MT-Safe tag:
https://www.gnu.org/software/libc/manual/html_node/POSIX-Safety-Concepts.html
If you want to identify thread-unsafe API for at least one libc or
unsure which libc will be used, use `any` (default).
.. title:: clang-tidy - concurrency-thread-canceltype-asynchronous
concurrency-thread-canceltype-asynchronous
==========================================
Finds ``pthread_setcanceltype`` function calls where a thread's cancellation
type is set to asynchronous. Asynchronous cancellation type
(``PTHREAD_CANCEL_ASYNCHRONOUS``) is generally unsafe, use type
``PTHREAD_CANCEL_DEFERRED`` instead which is the default. Even with deferred
cancellation, a cancellation point in an asynchronous signal handler may still
be acted upon and the effect is as if it was an asynchronous cancellation.
.. code-block: c++
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
This check corresponds to the CERT C Coding Standard rule
`POS47-C. Do not use threads that can be canceled asynchronously
<https://wiki.sei.cmu.edu/confluence/display/c/POS47-C.+Do+not+use+threads+that+can+be+canceled+asynchronously>`_.
.. title:: clang-tidy - cppcoreguidelines-avoid-c-arrays
.. meta::
:http-equiv=refresh: 5;URL=modernize-avoid-c-arrays.html
cppcoreguidelines-avoid-c-arrays
================================
The cppcoreguidelines-avoid-c-arrays check is an alias, please see
`modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-avoid-goto
cppcoreguidelines-avoid-goto
============================
The usage of ``goto`` for control flow is error prone and should be replaced
with looping constructs. Only forward jumps in nested loops are accepted.
This check implements `ES.76 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es76-avoid-goto>`_
from the CppCoreGuidelines and
`6.3.1 from High Integrity C++ <http://www.codingstandard.com/rule/6-3-1-ensure-that-the-labels-for-a-jump-statement-or-a-switch-condition-appear-later-in-the-same-or-an-enclosing-block/>`_.
For more information on why to avoid programming
with ``goto`` you can read the famous paper `A Case against the GO TO Statement. <https://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF>`_.
The check diagnoses ``goto`` for backward jumps in every language mode. These
should be replaced with `C/C++` looping constructs.
.. code-block:: c++
// Bad, handwritten for loop.
int i = 0;
// Jump label for the loop
loop_start:
do_some_operation();
if (i < 100) {
++i;
goto loop_start;
}
// Better
for(int i = 0; i < 100; ++i)
do_some_operation();
Modern C++ needs ``goto`` only to jump out of nested loops.
.. code-block:: c++
for(int i = 0; i < 100; ++i) {
for(int j = 0; j < 100; ++j) {
if (i * j > 500)
goto early_exit;
}
}
early_exit:
some_operation();
All other uses of ``goto`` are diagnosed in `C++`.
.. title:: clang-tidy - cppcoreguidelines-avoid-magic-numbers
.. meta::
:http-equiv=refresh: 5;URL=readability-magic-numbers.html
cppcoreguidelines-avoid-magic-numbers
=====================================
The cppcoreguidelines-avoid-magic-numbers check is an alias, please see
`readability-magic-numbers <readability-magic-numbers.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-avoid-non-const-global-variables
cppcoreguidelines-avoid-non-const-global-variables
==================================================
Finds non-const global variables as described in `I.2 of C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-global>`_ .
As `R.6 of C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rr-global>`_ is a duplicate of rule I.2 it also covers that rule.
.. code-block:: c++
char a; // Warns!
const char b = 0;
namespace some_namespace
{
char c; // Warns!
const char d = 0;
}
char * c_ptr1 = &some_namespace::c; // Warns!
char *const c_const_ptr = &some_namespace::c; // Warns!
char & c_reference = some_namespace::c; // Warns!
class Foo // No Warnings inside Foo, only namespace scope is covered
{
public:
char e = 0;
const char f = 0;
protected:
char g = 0;
private:
char h = 0;
};
Variables: ``a``, ``c``, ``c_ptr1``, ``c_ptr2``, ``c_const_ptr`` and
``c_reference``, will all generate warnings since they are either:
a globally accessible variable and non-const, a pointer or reference providing
global access to non-const data or both.
.. title:: clang-tidy - cppcoreguidelines-c-copy-assignment-signature
.. meta::
:http-equiv=refresh: 5;URL=misc-unconventional-assign-operator.html
cppcoreguidelines-c-copy-assignment-signature
=============================================
The cppcoreguidelines-c-copy-assignment-signature check is an alias, please see
`misc-unconventional-assign-operator <misc-unconventional-assign-operator.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-explicit-virtual-functions
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-override.html
cppcoreguidelines-explicit-virtual-functions
============================================
The cppcoreguidelines-explicit-virtual-functions check is an alias, please see
`modernize-use-override <modernize-use-override.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-init-variables
cppcoreguidelines-init-variables
================================
Checks whether there are local variables that are declared without an initial
value. These may lead to unexpected behaviour if there is a code path that reads
the variable before assigning to it.
Only integers, booleans, floats, doubles and pointers are checked. The fix
option initializes all detected values with the value of zero. An exception is
float and double types, which are initialized to NaN.
As an example a function that looks like this:
.. code-block:: c++
void function() {
int x;
char *txt;
double d;
// Rest of the function.
}
Would be rewritten to look like this:
.. code-block:: c++
#include <math.h>
void function() {
int x = 0;
char *txt = nullptr;
double d = NAN;
// Rest of the function.
}
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: MathHeader
A string specifying the header to include to get the definition of `NAN`.
Default is `<math.h>`.
.. title:: clang-tidy - cppcoreguidelines-interfaces-global-init
cppcoreguidelines-interfaces-global-init
========================================
This check flags initializers of globals that access extern objects,
and therefore can lead to order-of-initialization problems.
This rule is part of the "Interfaces" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-global-init
Note that currently this does not flag calls to non-constexpr functions, and
therefore globals could still be accessed from functions themselves.
.. title:: clang-tidy - cppcoreguidelines-macro-usage
cppcoreguidelines-macro-usage
=============================
Finds macro usage that is considered problematic because better language
constructs exist for the task.
The relevant sections in the C++ Core Guidelines are
`Enum.1 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum1-prefer-enumerations-over-macros>`_,
`ES.30 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es30-dont-use-macros-for-program-text-manipulation>`_,
`ES.31 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es31-dont-use-macros-for-constants-or-functions>`_ and
`ES.33 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es33-if-you-must-use-macros-give-them-unique-names>`_.
Options
-------
.. option:: AllowedRegexp
A regular expression to filter allowed macros. For example
`DEBUG*|LIBTORRENT*|TORRENT*|UNI*` could be applied to filter `libtorrent`.
Default value is `^DEBUG_*`.
.. option:: CheckCapsOnly
Boolean flag to warn on all macros except those with CAPS_ONLY names.
This option is intended to ease introduction of this check into older
code bases. Default value is `false`.
.. option:: IgnoreCommandLineMacros
Boolean flag to toggle ignoring command-line-defined macros.
Default value is `true`.
.. title:: clang-tidy - cppcoreguidelines-narrowing-conversions
cppcoreguidelines-narrowing-conversions
=======================================
Checks for silent narrowing conversions, e.g: ``int i = 0; i += 0.1;``. While
the issue is obvious in this former example, it might not be so in the
following: ``void MyClass::f(double d) { int_member_ += d; }``.
This rule is part of the "Expressions and statements" profile of the C++ Core
Guidelines, corresponding to rule ES.46. See
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es46-avoid-lossy-narrowing-truncating-arithmetic-conversions.
We enforce only part of the guideline, more specifically, we flag narrowing conversions from:
- an integer to a narrower integer (e.g. ``char`` to ``unsigned char``)
if WarnOnIntegerNarrowingConversion Option is set,
- an integer to a narrower floating-point (e.g. ``uint64_t`` to ``float``),
- a floating-point to an integer (e.g. ``double`` to ``int``),
- a floating-point to a narrower floating-point (e.g. ``double`` to ``float``)
if WarnOnFloatingPointNarrowingConversion Option is set.
This check will flag:
- All narrowing conversions that are not marked by an explicit cast (c-style or
``static_cast``). For example: ``int i = 0; i += 0.1;``,
``void f(int); f(0.1);``,
- All applications of binary operators with a narrowing conversions.
For example: ``int i; i+= 0.1;``.
Options
-------
.. option:: WarnOnIntegerNarrowingConversion
When `true`, the check will warn on narrowing integer conversion
(e.g. ``int`` to ``size_t``). `true` by default.
.. option:: WarnOnFloatingPointNarrowingConversion
When `true`, the check will warn on narrowing floating point conversion
(e.g. ``double`` to ``float``). `true` by default.
.. option:: WarnWithinTemplateInstantiation
When `true`, the check will warn on narrowing conversions within template
instantations. `false` by default.
.. option:: WarnOnEquivalentBitWidth
When `true`, the check will warn on narrowing conversions that arise from
casting between types of equivalent bit width. (e.g.
`int n = uint(0);` or `long long n = double(0);`) `true` by default.
.. option:: IgnoreConversionFromTypes
Narrowing conversions from any type in this semicolon-separated list will be
ignored. This may be useful to weed out commonly occurring, but less commonly
problematic assignments such as `int n = std::vector<char>().size();` or
`int n = std::difference(it1, it2);`. The default list is empty, but one
suggested list for a legacy codebase would be
`size_t;ptrdiff_t;size_type;difference_type`.
.. option:: PedanticMode
When `true`, the check will warn on assigning a floating point constant
to an integer value even if the floating point value is exactly
representable in the destination type (e.g. ``int i = 1.0;``).
`false` by default.
FAQ
---
- What does "narrowing conversion from 'int' to 'float'" mean?
An IEEE754 Floating Point number can represent all integer values in the range
[-2^PrecisionBits, 2^PrecisionBits] where PrecisionBits is the number of bits in
the mantissa.
For ``float`` this would be [-2^23, 2^23], where ``int`` can represent values in
the range [-2^31, 2^31-1].
- What does "implementation-defined" mean?
You may have encountered messages like "narrowing conversion from 'unsigned int'
to signed type 'int' is implementation-defined".
The C/C++ standard does not mandate two’s complement for signed integers, and so
the compiler is free to define what the semantics are for converting an unsigned
integer to signed integer. Clang's implementation uses the two’s complement
format.
.. title:: clang-tidy - cppcoreguidelines-no-malloc
cppcoreguidelines-no-malloc
===========================
This check handles C-Style memory management using ``malloc()``, ``realloc()``,
``calloc()`` and ``free()``. It warns about its use and tries to suggest the use
of an appropriate RAII object.
Furthermore, it can be configured to check against a user-specified list of functions
that are used for memory management (e.g. ``posix_memalign()``).
See `C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rr-mallocfree>`_.
There is no attempt made to provide fix-it hints, since manual resource
management isn't easily transformed automatically into RAII.
.. code-block:: c++
// Warns each of the following lines.
// Containers like std::vector or std::string should be used.
char* some_string = (char*) malloc(sizeof(char) * 20);
char* some_string = (char*) realloc(sizeof(char) * 30);
free(some_string);
int* int_array = (int*) calloc(30, sizeof(int));
// Rather use a smartpointer or stack variable.
struct some_struct* s = (struct some_struct*) malloc(sizeof(struct some_struct));
Options
-------
.. option:: Allocations
Semicolon-separated list of fully qualified names of memory allocation functions.
Defaults to ``::malloc;::calloc``.
.. option:: Deallocations
Semicolon-separated list of fully qualified names of memory allocation functions.
Defaults to ``::free``.
.. option:: Reallocations
Semicolon-separated list of fully qualified names of memory allocation functions.
Defaults to ``::realloc``.
.. title:: clang-tidy - cppcoreguidelines-non-private-member-variables-in-classes
.. meta::
:http-equiv=refresh: 5;URL=misc-non-private-member-variables-in-classes.html
cppcoreguidelines-non-private-member-variables-in-classes
=========================================================
The cppcoreguidelines-non-private-member-variables-in-classes check is an alias,
please see
`misc-non-private-member-variables-in-classes <misc-non-private-member-variables-in-classes.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-owning-memory
cppcoreguidelines-owning-memory
===============================
This check implements the type-based semantics of ``gsl::owner<T*>``, which allows
static analysis on code, that uses raw pointers to handle resources like
dynamic memory, but won't introduce RAII concepts.
The relevant sections in the `C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md>`_ are I.11, C.33, R.3 and GSL.Views
The definition of a ``gsl::owner<T*>`` is straight forward
.. code-block:: c++
namespace gsl { template <typename T> owner = T; }
It is therefore simple to introduce the owner even without using an implementation of
the `Guideline Support Library <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#gsl-guideline-support-library>`_.
All checks are purely type based and not (yet) flow sensitive.
The following examples will demonstrate the correct and incorrect initializations
of owners, assignment is handled the same way. Note that both ``new`` and
``malloc()``-like resource functions are considered to produce resources.
.. code-block:: c++
// Creating an owner with factory functions is checked.
gsl::owner<int*> function_that_returns_owner() { return gsl::owner<int*>(new int(42)); }
// Dynamic memory must be assigned to an owner
int* Something = new int(42); // BAD, will be caught
gsl::owner<int*> Owner = new int(42); // Good
gsl::owner<int*> Owner = new int[42]; // Good as well
// Returned owner must be assigned to an owner
int* Something = function_that_returns_owner(); // Bad, factory function
gsl::owner<int*> Owner = function_that_returns_owner(); // Good, result lands in owner
// Something not a resource or owner should not be assigned to owners
int Stack = 42;
gsl::owner<int*> Owned = &Stack; // Bad, not a resource assigned
In the case of dynamic memory as resource, only ``gsl::owner<T*>`` variables are allowed
to be deleted.
.. code-block:: c++
// Example Bad, non-owner as resource handle, will be caught.
int* NonOwner = new int(42); // First warning here, since new must land in an owner
delete NonOwner; // Second warning here, since only owners are allowed to be deleted
// Example Good, Ownership correctly stated
gsl::owner<int*> Owner = new int(42); // Good
delete Owner; // Good as well, statically enforced, that only owners get deleted
The check will furthermore ensure, that functions, that expect a ``gsl::owner<T*>`` as
argument get called with either a ``gsl::owner<T*>`` or a newly created resource.
.. code-block:: c++
void expects_owner(gsl::owner<int*> o) { delete o; }
// Bad Code
int NonOwner = 42;
expects_owner(&NonOwner); // Bad, will get caught
// Good Code
gsl::owner<int*> Owner = new int(42);
expects_owner(Owner); // Good
expects_owner(new int(42)); // Good as well, recognized created resource
// Port legacy code for better resource-safety
gsl::owner<FILE*> File = fopen("my_file.txt", "rw+");
FILE* BadFile = fopen("another_file.txt", "w"); // Bad, warned
// ... use the file
fclose(File); // Ok, File is annotated as 'owner<>'
fclose(BadFile); // BadFile is not an 'owner<>', will be warned
Options
-------
.. option:: LegacyResourceProducers
Semicolon-separated list of fully qualified names of legacy functions that create
resources but cannot introduce ``gsl::owner<>``.
Defaults to ``::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile``.
.. option:: LegacyResourceConsumers
Semicolon-separated list of fully qualified names of legacy functions expecting
resource owners as pointer arguments but cannot introduce ``gsl::owner<>``.
Defaults to ``::free;::realloc;::freopen;::fclose``.
Limitations
-----------
Using ``gsl::owner<T*>`` in a typedef or alias is not handled correctly.
.. code-block:: c++
using heap_int = gsl::owner<int*>;
heap_int allocated = new int(42); // False positive!
The ``gsl::owner<T*>`` is declared as a templated type alias.
In template functions and classes, like in the example below, the information
of the type aliases gets lost. Therefore using ``gsl::owner<T*>`` in a heavy templated
code base might lead to false positives.
Known code constructs that do not get diagnosed correctly are:
- ``std::exchange``
- ``std::vector<gsl::owner<T*>>``
.. code-block:: c++
// This template function works as expected. Type information doesn't get lost.
template <typename T>
void delete_owner(gsl::owner<T*> owned_object) {
delete owned_object; // Everything alright
}
gsl::owner<int*> function_that_returns_owner() { return gsl::owner<int*>(new int(42)); }
// Type deduction does not work for auto variables.
// This is caught by the check and will be noted accordingly.
auto OwnedObject = function_that_returns_owner(); // Type of OwnedObject will be int*
// Problematic function template that looses the typeinformation on owner
template <typename T>
void bad_template_function(T some_object) {
// This line will trigger the warning, that a non-owner is assigned to an owner
gsl::owner<T*> new_owner = some_object;
}
// Calling the function with an owner still yields a false positive.
bad_template_function(gsl::owner<int*>(new int(42)));
// The same issue occurs with templated classes like the following.
template <typename T>
class OwnedValue {
public:
const T getValue() const { return _val; }
private:
T _val;
};
// Code, that yields a false positive.
OwnedValue<gsl::owner<int*>> Owner(new int(42)); // Type deduction yield T -> int *
// False positive, getValue returns int* and not gsl::owner<int*>
gsl::owner<int*> OwnedInt = Owner.getValue();
Another limitation of the current implementation is only the type based checking.
Suppose you have code like the following:
.. code-block:: c++
// Two owners with assigned resources
gsl::owner<int*> Owner1 = new int(42);
gsl::owner<int*> Owner2 = new int(42);
Owner2 = Owner1; // Conceptual Leak of initial resource of Owner2!
Owner1 = nullptr;
The semantic of a ``gsl::owner<T*>`` is mostly like a ``std::unique_ptr<T>``, therefore
assignment of two ``gsl::owner<T*>`` is considered a move, which requires that the
resource ``Owner2`` must have been released before the assignment.
This kind of condition could be caught in later improvements of this check with
flowsensitive analysis. Currently, the `Clang Static Analyzer` catches this bug
for dynamic memory, but not for general types of resources.
.. title:: clang-tidy - cppcoreguidelines-prefer-member-initializer
cppcoreguidelines-prefer-member-initializer
===========================================
Finds member initializations in the constructor body which can be converted
into member initializers of the constructor instead. This not only improves
the readability of the code but also positively affects its performance.
Class-member assignments inside a control statement or following the first
control statement are ignored.
This check implements `C.49 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c49-prefer-initialization-to-assignment-in-constructors>`_ from the CppCoreGuidelines.
If the language version is `C++ 11` or above, the constructor is the default
constructor of the class, the field is not a bitfield (only in case of earlier
language version than `C++ 20`), furthermore the assigned value is a literal,
negated literal or ``enum`` constant then the preferred place of the
initialization is at the class member declaration.
This latter rule is `C.48 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c48-prefer-in-class-initializers-to-member-initializers-in-constructors-for-constant-initializers>`_ from CppCoreGuidelines.
Please note, that this check does not enforce this latter rule for
initializations already implemented as member initializers. For that purpose
see check `modernize-use-default-member-init <modernize-use-default-member-init.html>`_.
Example 1
---------
.. code-block:: c++
class C {
int n;
int m;
public:
C() {
n = 1; // Literal in default constructor
if (dice())
return;
m = 1;
}
};
Here ``n`` can be initialized using a default member initializer, unlike
``m``, as ``m``'s initialization follows a control statement (``if``):
.. code-block:: c++
class C {
int n{1};
int m;
public:
C() {
if (dice())
return;
m = 1;
}
Example 2
---------
.. code-block:: c++
class C {
int n;
int m;
public:
C(int nn, int mm) {
n = nn; // Neither default constructor nor literal
if (dice())
return;
m = mm;
}
};
Here ``n`` can be initialized in the constructor initialization list, unlike
``m``, as ``m``'s initialization follows a control statement (``if``):
.. code-block:: c++
C(int nn, int mm) : n(nn) {
if (dice())
return;
m = mm;
}
.. option:: UseAssignment
If this option is set to `true` (default is `false`), the check will initialize
members with an assignment. In this case the fix of the first example looks
like this:
.. code-block:: c++
class C {
int n = 1;
int m;
public:
C() {
if (dice())
return;
m = 1;
}
};
.. title:: clang-tidy - cppcoreguidelines-pro-bounds-array-to-pointer-decay
cppcoreguidelines-pro-bounds-array-to-pointer-decay
===================================================
This check flags all array to pointer decays.
Pointers should not be used as arrays. ``span<T>`` is a bounds-checked, safe
alternative to using pointers to access arrays.
This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-decay.
.. title:: clang-tidy - cppcoreguidelines-pro-bounds-constant-array-index
cppcoreguidelines-pro-bounds-constant-array-index
=================================================
This check flags all array subscript expressions on static arrays and
``std::arrays`` that either do not have a constant integer expression index or
are out of bounds (for ``std::array``). For out-of-bounds checking of static
arrays, see the `-Warray-bounds` Clang diagnostic.
This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-arrayindex.
Options
-------
.. option:: GslHeader
The check can generate fixes after this option has been set to the name of
the include file that contains ``gsl::at()``, e.g. `"gsl/gsl.h"`.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. title:: clang-tidy - cppcoreguidelines-pro-bounds-pointer-arithmetic
cppcoreguidelines-pro-bounds-pointer-arithmetic
===============================================
This check flags all usage of pointer arithmetic, because it could lead to an
invalid pointer. Subtraction of two pointers is not flagged by this check.
Pointers should only refer to single objects, and pointer arithmetic is fragile
and easy to get wrong. ``span<T>`` is a bounds-checked, safe type for accessing
arrays of data.
This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-arithmetic.
.. title:: clang-tidy - cppcoreguidelines-pro-type-const-cast
cppcoreguidelines-pro-type-const-cast
=====================================
This check flags all uses of ``const_cast`` in C++ code.
Modifying a variable that was declared const is undefined behavior, even with
``const_cast``.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-constcast.
.. title:: clang-tidy - cppcoreguidelines-pro-type-cstyle-cast
cppcoreguidelines-pro-type-cstyle-cast
======================================
This check flags all use of C-style casts that perform a ``static_cast``
downcast, ``const_cast``, or ``reinterpret_cast``.
Use of these casts can violate type safety and cause the program to access a
variable that is actually of type X to be accessed as if it were of an unrelated
type Z. Note that a C-style ``(T)expression`` cast means to perform the first of
the following that is possible: a ``const_cast``, a ``static_cast``, a
``static_cast`` followed by a ``const_cast``, a ``reinterpret_cast``, or a
``reinterpret_cast`` followed by a ``const_cast``. This rule bans
``(T)expression`` only when used to perform an unsafe cast.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-cstylecast.
.. title:: clang-tidy - cppcoreguidelines-pro-type-member-init
cppcoreguidelines-pro-type-member-init
======================================
The check flags user-defined constructor definitions that do not
initialize all fields that would be left in an undefined state by
default construction, e.g. builtins, pointers and record types without
user-provided default constructors containing at least one such
type. If these fields aren't initialized, the constructor will leave
some of the memory in an undefined state.
For C++11 it suggests fixes to add in-class field initializers. For
older versions it inserts the field initializers into the constructor
initializer list. It will also initialize any direct base classes that
need to be zeroed in the constructor initializer list.
The check takes assignment of fields in the constructor body into
account but generates false positives for fields initialized in
methods invoked in the constructor body.
The check also flags variables with automatic storage duration that have record
types without a user-provided constructor and are not initialized. The suggested
fix is to zero initialize the variable via ``{}`` for C++11 and beyond or ``=
{}`` for older language versions.
Options
-------
.. option:: IgnoreArrays
If set to `true`, the check will not warn about array members that are not
zero-initialized during construction. For performance critical code, it may
be important to not initialize fixed-size array members. Default is `false`.
.. option:: UseAssignment
If set to `true`, the check will provide fix-its with literal initializers
\( ``int i = 0;`` \) instead of curly braces \( ``int i{};`` \).
This rule is part of the "Type safety" profile of the C++ Core
Guidelines, corresponding to rule Type.6. See
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-memberinit.
.. title:: clang-tidy - cppcoreguidelines-pro-type-reinterpret-cast
cppcoreguidelines-pro-type-reinterpret-cast
===========================================
This check flags all uses of ``reinterpret_cast`` in C++ code.
Use of these casts can violate type safety and cause the program to access a
variable that is actually of type ``X`` to be accessed as if it were of an
unrelated type ``Z``.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-reinterpretcast.
.. title:: clang-tidy - cppcoreguidelines-pro-type-static-cast-downcast
cppcoreguidelines-pro-type-static-cast-downcast
===============================================
This check flags all usages of ``static_cast``, where a base class is casted to
a derived class. In those cases, a fix-it is provided to convert the cast to a
``dynamic_cast``.
Use of these casts can violate type safety and cause the program to access a
variable that is actually of type ``X`` to be accessed as if it were of an
unrelated type ``Z``.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-downcast.
.. title:: clang-tidy - cppcoreguidelines-pro-type-union-access
cppcoreguidelines-pro-type-union-access
=======================================
This check flags all access to members of unions. Passing unions as a whole is
not flagged.
Reading from a union member assumes that member was the last one written, and
writing to a union member assumes another member with a nontrivial destructor
had its destructor called. This is fragile because it cannot generally be
enforced to be safe in the language and so relies on programmer discipline to
get it right.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-unions.
.. title:: clang-tidy - cppcoreguidelines-pro-type-vararg
cppcoreguidelines-pro-type-vararg
=================================
This check flags all calls to c-style vararg functions and all use of
``va_arg``.
To allow for SFINAE use of vararg functions, a call is not flagged if a literal
0 is passed as the only vararg argument.
Passing to varargs assumes the correct type will be read. This is fragile
because it cannot generally be enforced to be safe in the language and so relies
on programmer discipline to get it right.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-varargs.
.. title:: clang-tidy - cppcoreguidelines-slicing
cppcoreguidelines-slicing
=========================
Flags slicing of member variables or vtable. Slicing happens when copying a
derived object into a base object: the members of the derived object (both
member variables and virtual member functions) will be discarded. This can be
misleading especially for member function slicing, for example:
.. code-block:: c++
struct B { int a; virtual int f(); };
struct D : B { int b; int f() override; };
void use(B b) { // Missing reference, intended?
b.f(); // Calls B::f.
}
D d;
use(d); // Slice.
See the relevant C++ Core Guidelines sections for details:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es63-dont-slice
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c145-access-polymorphic-objects-through-pointers-and-references
.. title:: clang-tidy - cppcoreguidelines-special-member-functions
cppcoreguidelines-special-member-functions
==========================================
The check finds classes where some but not all of the special member functions
are defined.
By default the compiler defines a copy constructor, copy assignment operator,
move constructor, move assignment operator and destructor. The default can be
suppressed by explicit user-definitions. The relationship between which
functions will be suppressed by definitions of other functions is complicated
and it is advised that all five are defaulted or explicitly defined.
Note that defining a function with ``= delete`` is considered to be a
definition.
This rule is part of the "Constructors, assignments, and destructors" profile of the C++ Core
Guidelines, corresponding to rule C.21. See
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all.
Options
-------
.. option:: AllowSoleDefaultDtor
When set to `true` (default is `false`), this check doesn't flag classes with a sole, explicitly
defaulted destructor. An example for such a class is:
.. code-block:: c++
struct A {
virtual ~A() = default;
};
.. option:: AllowMissingMoveFunctions
When set to `true` (default is `false`), this check doesn't flag classes which define no move
operations at all. It still flags classes which define only one of either
move constructor or move assignment operator. With this option enabled, the following class won't be flagged:
.. code-block:: c++
struct A {
A(const A&);
A& operator=(const A&);
~A();
};
.. option:: AllowMissingMoveFunctionsWhenCopyIsDeleted
When set to `true` (default is `false`), this check doesn't flag classes which define deleted copy
operations but don't define move operations. This flags is related to Google C++ Style Guide
https://google.github.io/styleguide/cppguide.html#Copyable_Movable_Types. With this option enabled, the
following class won't be flagged:
.. code-block:: c++
struct A {
A(const A&) = delete;
A& operator=(const A&) = delete;
~A();
};
.. title:: clang-tidy - darwin-avoid-spinlock
darwin-avoid-spinlock
=====================
Finds usages of ``OSSpinlock``, which is deprecated due to potential livelock
problems.
This check will detect following function invocations:
- ``OSSpinlockLock``
- ``OSSpinlockTry``
- ``OSSpinlockUnlock``
The corresponding information about the problem of ``OSSpinlock``: https://blog.postmates.com/why-spinlocks-are-bad-on-ios-b69fc5221058
.. title:: clang-tidy - darwin-dispatch-once-nonstatic
darwin-dispatch-once-nonstatic
==============================
Finds declarations of ``dispatch_once_t`` variables without static or global
storage. The behavior of using ``dispatch_once_t`` predicates with automatic or
dynamic storage is undefined by libdispatch, and should be avoided.
It is a common pattern to have functions initialize internal static or global
data once when the function runs, but programmers have been known to miss the
static on the ``dispatch_once_t`` predicate, leading to an uninitialized flag
value at the mercy of the stack.
Programmers have also been known to make ``dispatch_once_t`` variables be
members of structs or classes, with the intent to lazily perform some expensive
struct or class member initialization only once; however, this violates the
libdispatch requirements.
See the discussion section of
`Apple's dispatch_once documentation <https://developer.apple.com/documentation/dispatch/1447169-dispatch_once>`_
for more information.
.. title:: clang-tidy - fuchsia-default-arguments-calls
fuchsia-default-arguments-calls
===============================
Warns if a function or method is called with default arguments.
For example, given the declaration:
.. code-block:: c++
int foo(int value = 5) { return value; }
A function call expression that uses a default argument will be diagnosed.
Calling it without defaults will not cause a warning:
.. code-block:: c++
foo(); // warning
foo(0); // no warning
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-default-arguments-declarations
fuchsia-default-arguments-declarations
======================================
Warns if a function or method is declared with default parameters.
For example, the declaration:
.. code-block:: c++
int foo(int value = 5) { return value; }
will cause a warning.
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-header-anon-namespaces
.. meta::
:http-equiv=refresh: 5;URL=google-build-namespaces.html
fuchsia-header-anon-namespaces
==============================
The fuchsia-header-anon-namespaces check is an alias, please see
`google-build-namespace <google-build-namespaces.html>`_
for more information.
.. title:: clang-tidy - fuchsia-multiple-inheritance
fuchsia-multiple-inheritance
============================
Warns if a class inherits from multiple classes that are not pure virtual.
For example, declaring a class that inherits from multiple concrete classes is
disallowed:
.. code-block:: c++
class Base_A {
public:
virtual int foo() { return 0; }
};
class Base_B {
public:
virtual int bar() { return 0; }
};
// Warning
class Bad_Child1 : public Base_A, Base_B {};
A class that inherits from a pure virtual is allowed:
.. code-block:: c++
class Interface_A {
public:
virtual int foo() = 0;
};
class Interface_B {
public:
virtual int bar() = 0;
};
// No warning
class Good_Child1 : public Interface_A, Interface_B {
virtual int foo() override { return 0; }
virtual int bar() override { return 0; }
};
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-overloaded-operator
fuchsia-overloaded-operator
===========================
Warns if an operator is overloaded, except for the assignment (copy and move)
operators.
For example:
.. code-block:: c++
int operator+(int); // Warning
B &operator=(const B &Other); // No warning
B &operator=(B &&Other) // No warning
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-statically-constructed-objects
fuchsia-statically-constructed-objects
======================================
Warns if global, non-trivial objects with static storage are constructed, unless
the object is statically initialized with a ``constexpr`` constructor or has no
explicit constructor.
For example:
.. code-block:: c++
class A {};
class B {
public:
B(int Val) : Val(Val) {}
private:
int Val;
};
class C {
public:
C(int Val) : Val(Val) {}
constexpr C() : Val(0) {}
private:
int Val;
};
static A a; // No warning, as there is no explicit constructor
static C c(0); // No warning, as constructor is constexpr
static B b(0); // Warning, as constructor is not constexpr
static C c2(0, 1); // Warning, as constructor is not constexpr
static int i; // No warning, as it is trivial
extern int get_i();
static C(get_i()) // Warning, as the constructor is dynamically initialized
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-trailing-return
fuchsia-trailing-return
=======================
Functions that have trailing returns are disallowed, except for those using
``decltype`` specifiers and lambda with otherwise unutterable return types.
For example:
.. code-block:: c++
// No warning
int add_one(const int arg) { return arg; }
// Warning
auto get_add_one() -> int (*)(const int) {
return add_one;
}
Exceptions are made for lambdas and ``decltype`` specifiers:
.. code-block:: c++
// No warning
auto lambda = [](double x, double y) -> double {return x + y;};
// No warning
template <typename T1, typename T2>
auto fn(const T1 &lhs, const T2 &rhs) -> decltype(lhs + rhs) {
return lhs + rhs;
}
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-virtual-inheritance
fuchsia-virtual-inheritance
===========================
Warns if classes are defined with virtual inheritance.
For example, classes should not be defined with virtual inheritance:
.. code-block:: c++
class B : public virtual A {}; // warning
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - google-build-explicit-make-pair
google-build-explicit-make-pair
===============================
Check that ``make_pair``'s template arguments are deduced.
G++ 4.6 in C++11 mode fails badly if ``make_pair``'s template arguments are
specified explicitly, and such use isn't intended in any case.
Corresponding cpplint.py check name: `build/explicit_make_pair`.
.. title:: clang-tidy - google-build-namespaces
google-build-namespaces
=======================
`cert-dcl59-cpp` redirects here as an alias for this check.
`fuchsia-header-anon-namespaces` redirects here as an alias for this check.
Finds anonymous namespaces in headers.
https://google.github.io/styleguide/cppguide.html#Namespaces
Corresponding cpplint.py check name: `build/namespaces`.
Options
-------
.. option:: HeaderFileExtensions
A comma-separated list of filename extensions of header files (the filename
extensions should not include "." prefix). Default is "h,hh,hpp,hxx".
For header files without an extension, use an empty string (if there are no
other desired extensions) or leave an empty element in the list. e.g.,
"h,hh,hpp,hxx," (note the trailing comma).
.. title:: clang-tidy - google-build-using-namespace
google-build-using-namespace
============================
Finds ``using namespace`` directives.
The check implements the following rule of the
`Google C++ Style Guide <https://google.github.io/styleguide/cppguide.html#Namespaces>`_:
You may not use a using-directive to make all names from a namespace
available.
.. code-block:: c++
// Forbidden -- This pollutes the namespace.
using namespace foo;
Corresponding cpplint.py check name: `build/namespaces`.
.. title:: clang-tidy - google-default-arguments
google-default-arguments
========================
Checks that default arguments are not given for virtual methods.
See https://google.github.io/styleguide/cppguide.html#Default_Arguments
.. title:: clang-tidy - google-explicit-constructor
google-explicit-constructor
===========================
Checks that constructors callable with a single argument and conversion
operators are marked explicit to avoid the risk of unintentional implicit
conversions.
Consider this example:
.. code-block:: c++
struct S {
int x;
operator bool() const { return true; }
};
bool f() {
S a{1};
S b{2};
return a == b;
}
The function will return ``true``, since the objects are implicitly converted to
``bool`` before comparison, which is unlikely to be the intent.
The check will suggest inserting ``explicit`` before the constructor or
conversion operator declaration. However, copy and move constructors should not
be explicit, as well as constructors taking a single ``initializer_list``
argument.
This code:
.. code-block:: c++
struct S {
S(int a);
explicit S(const S&);
operator bool() const;
...
will become
.. code-block:: c++
struct S {
explicit S(int a);
S(const S&);
explicit operator bool() const;
...
See https://google.github.io/styleguide/cppguide.html#Explicit_Constructors
.. title:: clang-tidy - google-global-names-in-headers
google-global-names-in-headers
==============================
Flag global namespace pollution in header files. Right now it only triggers on
``using`` declarations and directives.
The relevant style guide section is
https://google.github.io/styleguide/cppguide.html#Namespaces.
Options
-------
.. option:: HeaderFileExtensions
A comma-separated list of filename extensions of header files (the filename
extensions should not contain "." prefix). Default is "h".
For header files without an extension, use an empty string (if there are no
other desired extensions) or leave an empty element in the list. e.g.,
"h,hh,hpp,hxx," (note the trailing comma).
.. title:: clang-tidy - google-objc-avoid-nsobject-new
google-objc-avoid-nsobject-new
==============================
Finds calls to ``+new`` or overrides of it, which are prohibited by the
Google Objective-C style guide.
The Google Objective-C style guide forbids calling ``+new`` or overriding it in
class implementations, preferring ``+alloc`` and ``-init`` methods to
instantiate objects.
An example:
.. code-block:: objc
NSDate *now = [NSDate new];
Foo *bar = [Foo new];
Instead, code should use ``+alloc``/``-init`` or class factory methods.
.. code-block:: objc
NSDate *now = [NSDate date];
Foo *bar = [[Foo alloc] init];
This check corresponds to the Google Objective-C Style Guide rule
`Do Not Use +new
<https://google.github.io/styleguide/objcguide.html#do-not-use-new>`_.
.. title:: clang-tidy - google-objc-avoid-throwing-exception
google-objc-avoid-throwing-exception
====================================
Finds uses of throwing exceptions usages in Objective-C files.
For the same reason as the Google C++ style guide, we prefer not throwing
exceptions from Objective-C code.
The corresponding C++ style guide rule:
https://google.github.io/styleguide/cppguide.html#Exceptions
Instead, prefer passing in ``NSError **`` and return ``BOOL`` to indicate success or failure.
A counterexample:
.. code-block:: objc
- (void)readFile {
if ([self isError]) {
@throw [NSException exceptionWithName:...];
}
}
Instead, returning an error via ``NSError **`` is preferred:
.. code-block:: objc
- (BOOL)readFileWithError:(NSError **)error {
if ([self isError]) {
*error = [NSError errorWithDomain:...];
return NO;
}
return YES;
}
The corresponding style guide rule:
https://google.github.io/styleguide/objcguide.html#avoid-throwing-exceptions
.. title:: clang-tidy - google-objc-function-naming
google-objc-function-naming
===========================
Finds function declarations in Objective-C files that do not follow the pattern
described in the Google Objective-C Style Guide.
The corresponding style guide rule can be found here:
https://google.github.io/styleguide/objcguide.html#function-names
All function names should be in Pascal case. Functions whose storage class is
not static should have an appropriate prefix.
The following code sample does not follow this pattern:
.. code-block:: objc
static bool is_positive(int i) { return i > 0; }
bool IsNegative(int i) { return i < 0; }
The sample above might be corrected to the following code:
.. code-block:: objc
static bool IsPositive(int i) { return i > 0; }
bool *ABCIsNegative(int i) { return i < 0; }
.. title:: clang-tidy - google-objc-global-variable-declaration
google-objc-global-variable-declaration
=======================================
Finds global variable declarations in Objective-C files that do not follow the
pattern of variable names in Google's Objective-C Style Guide.
The corresponding style guide rule:
https://google.github.io/styleguide/objcguide.html#variable-names
All the global variables should follow the pattern of ``g[A-Z].*`` (variables) or
``k[A-Z].*`` (constants). The check will suggest a variable name that follows the
pattern if it can be inferred from the original name.
For code:
.. code-block:: objc
static NSString* myString = @"hello";
The fix will be:
.. code-block:: objc
static NSString* gMyString = @"hello";
Another example of constant:
.. code-block:: objc
static NSString* const myConstString = @"hello";
The fix will be:
.. code-block:: objc
static NSString* const kMyConstString = @"hello";
However for code that prefixed with non-alphabetical characters like:
.. code-block:: objc
static NSString* __anotherString = @"world";
The check will give a warning message but will not be able to suggest a fix. The
user needs to fix it on their own.
.. title:: clang-tidy - google-readability-avoid-underscore-in-googletest-name
google-readability-avoid-underscore-in-googletest-name
======================================================
Checks whether there are underscores in googletest test and test case names in
test macros:
- ``TEST``
- ``TEST_F``
- ``TEST_P``
- ``TYPED_TEST``
- ``TYPED_TEST_P``
The ``FRIEND_TEST`` macro is not included.
For example:
.. code-block:: c++
TEST(TestCaseName, Illegal_TestName) {}
TEST(Illegal_TestCaseName, TestName) {}
would trigger the check. `Underscores are not allowed`_ in test names nor test
case names.
The ``DISABLED_`` prefix, which may be used to `disable individual tests`_, is
ignored when checking test names, but the rest of the rest of the test name is
still checked.
This check does not propose any fixes.
.. _Underscores are not allowed: https://github.com/google/googletest/blob/master/googletest/docs/faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore
.. _disable individual tests: https://github.com/google/googletest/blob/master/googletest/docs/faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore
.. title:: clang-tidy - google-readability-braces-around-statements
.. meta::
:http-equiv=refresh: 5;URL=readability-braces-around-statements.html
google-readability-braces-around-statements
===========================================
The google-readability-braces-around-statements check is an alias, please see
`readability-braces-around-statements <readability-braces-around-statements.html>`_
for more information.
.. title:: clang-tidy - google-readability-casting
google-readability-casting
==========================
Finds usages of C-style casts.
https://google.github.io/styleguide/cppguide.html#Casting
Corresponding cpplint.py check name: `readability/casting`.
This check is similar to ``-Wold-style-cast``, but it suggests automated fixes
in some cases. The reported locations should not be different from the
ones generated by ``-Wold-style-cast``.
.. title:: clang-tidy - google-readability-function-size
.. meta::
:http-equiv=refresh: 5;URL=readability-function-size.html
google-readability-function-size
================================
The google-readability-function-size check is an alias, please see
`readability-function-size <readability-function-size.html>`_ for more
information.
.. title:: clang-tidy - google-readability-namespace-comments
.. meta::
:http-equiv=refresh: 5;URL=llvm-namespace-comment.html
google-readability-namespace-comments
=====================================
The google-readability-namespace-comments check is an alias, please see
`llvm-namespace-comment <llvm-namespace-comment.html>`_ for more information.
.. title:: clang-tidy - google-readability-todo
google-readability-todo
=======================
Finds TODO comments without a username or bug number.
The relevant style guide section is
https://google.github.io/styleguide/cppguide.html#TODO_Comments.
Corresponding cpplint.py check: `readability/todo`
.. title:: clang-tidy - google-runtime-int
google-runtime-int
==================
Finds uses of ``short``, ``long`` and ``long long`` and suggest replacing them
with ``u?intXX(_t)?``.
The corresponding style guide rule:
https://google.github.io/styleguide/cppguide.html#Integer_Types.
Corresponding cpplint.py check: `runtime/int`.
Options
-------
.. option:: UnsignedTypePrefix
A string specifying the unsigned type prefix. Default is `uint`.
.. option:: SignedTypePrefix
A string specifying the signed type prefix. Default is `int`.
.. option:: TypeSuffix
A string specifying the type suffix. Default is an empty string.
.. title:: clang-tidy - google-runtime-operator
google-runtime-operator
=======================
Finds overloads of unary ``operator &``.
https://google.github.io/styleguide/cppguide.html#Operator_Overloading
Corresponding cpplint.py check name: `runtime/operator`.
.. title:: clang-tidy - google-upgrade-googletest-case
google-upgrade-googletest-case
==============================
Finds uses of deprecated Google Test version 1.9 APIs with names containing
``case`` and replaces them with equivalent APIs with ``suite``.
All names containing ``case`` are being replaced to be consistent with the
meanings of "test case" and "test suite" as used by the International
Software Testing Qualifications Board and ISO 29119.
The new names are a part of Google Test version 1.9 (release pending). It is
recommended that users update their dependency to version 1.9 and then use this
check to remove deprecated names.
The affected APIs are:
- Member functions of ``testing::Test``, ``testing::TestInfo``,
``testing::TestEventListener``, ``testing::UnitTest``, and any type inheriting
from these types
- The macros ``TYPED_TEST_CASE``, ``TYPED_TEST_CASE_P``,
``REGISTER_TYPED_TEST_CASE_P``, and ``INSTANTIATE_TYPED_TEST_CASE_P``
- The type alias ``testing::TestCase``
Examples of fixes created by this check:
.. code-block:: c++
class FooTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
};
TYPED_TEST_CASE(BarTest, BarTypes);
becomes
.. code-block:: c++
class FooTest : public testing::Test {
public:
static void SetUpTestSuite();
static void TearDownTestSuite();
};
TYPED_TEST_SUITE(BarTest, BarTypes);
For better consistency of user code, the check renames both virtual and
non-virtual member functions with matching names in derived types. The check
tries to provide a only warning when a fix cannot be made safely, as is the case
with some template and macro uses.
.. title:: clang-tidy - hicpp-avoid-c-arrays
.. meta::
:http-equiv=refresh: 5;URL=modernize-avoid-c-arrays.html
hicpp-avoid-c-arrays
====================
The hicpp-avoid-c-arrays check is an alias, please see
`modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_
for more information.
.. title:: clang-tidy - hicpp-avoid-goto
hicpp-avoid-goto
================
The `hicpp-avoid-goto` check is an alias to
`cppcoreguidelines-avoid-goto <cppcoreguidelines-avoid-goto.html>`_.
Rule `6.3.1 High Integrity C++ <http://www.codingstandard.com/rule/6-3-1-ensure-that-the-labels-for-a-jump-statement-or-a-switch-condition-appear-later-in-the-same-or-an-enclosing-block/>`_
requires that ``goto`` only skips parts of a block and is not used for other
reasons.
Both coding guidelines implement the same exception to the usage of ``goto``.
.. title:: clang-tidy - hicpp-braces-around-statements
.. meta::
:http-equiv=refresh: 5;URL=readability-braces-around-statements.html
hicpp-braces-around-statements
==============================
The `hicpp-braces-around-statements` check is an alias, please see
`readability-braces-around-statements <readability-braces-around-statements.html>`_
for more information.
It enforces the `rule 6.1.1 <http://www.codingstandard.com/rule/6-1-1-enclose-the-body-of-a-selection-or-an-iteration-statement-in-a-compound-statement/>`_.
.. title:: clang-tidy - hicpp-deprecated-headers
.. meta::
:http-equiv=refresh: 5;URL=modernize-deprecated-headers.html
hicpp-deprecated-headers
========================
The `hicpp-deprecated-headers` check is an alias, please see
`modernize-deprecated-headers <modernize-deprecated-headers.html>`_
for more information.
It enforces the `rule 1.3.3 <http://www.codingstandard.com/rule/1-3-3-do-not-use-the-c-standard-library-h-headers/>`_.
.. title:: clang-tidy - hicpp-exception-baseclass
hicpp-exception-baseclass
=========================
Ensure that every value that in a ``throw`` expression is an instance of
``std::exception``.
This enforces `rule 15.1 <http://www.codingstandard.com/section/15-1-throwing-an-exception/>`_
of the High Integrity C++ Coding Standard.
.. code-block:: c++
class custom_exception {};
void throwing() noexcept(false) {
// Problematic throw expressions.
throw int(42);
throw custom_exception();
}
class mathematical_error : public std::exception {};
void throwing2() noexcept(false) {
// These kind of throws are ok.
throw mathematical_error();
throw std::runtime_error();
throw std::exception();
}
.. title:: clang-tidy - hicpp-explicit-conversions
.. meta::
:http-equiv=refresh: 5;URL=google-explicit-constructor.html
hicpp-explicit-conversions
==========================
This check is an alias for `google-explicit-constructor <google-explicit-constructor.html>`_.
Used to enforce parts of `rule 5.4.1 <http://www.codingstandard.com/rule/5-4-1-only-use-casting-forms-static_cast-excl-void-dynamic_cast-or-explicit-constructor-call/>`_.
This check will enforce that constructors and conversion operators are marked `explicit`.
Other forms of casting checks are implemented in other places.
The following checks can be used to check for more forms of casting:
- `cppcoreguidelines-pro-type-static-cast-downcast <cppcoreguidelines-pro-type-static-cast-downcast.html>`_
- `cppcoreguidelines-pro-type-reinterpret-cast <cppcoreguidelines-pro-type-reinterpret-cast.html>`_
- `cppcoreguidelines-pro-type-const-cast <cppcoreguidelines-pro-type-const-cast.html>`_
- `cppcoreguidelines-pro-type-cstyle-cast <cppcoreguidelines-pro-type-cstyle-cast.html>`_
.. title:: clang-tidy - hicpp-function-size
.. meta::
:http-equiv=refresh: 5;URL=readability-function-size.html
hicpp-function-size
===================
This check is an alias for `readability-function-size <readability-function-size.html>`_.
Useful to enforce multiple sections on function complexity.
- `rule 8.2.2 <http://www.codingstandard.com/rule/8-2-2-do-not-declare-functions-with-an-excessive-number-of-parameters/>`_
- `rule 8.3.1 <http://www.codingstandard.com/rule/8-3-1-do-not-write-functions-with-an-excessive-mccabe-cyclomatic-complexity/>`_
- `rule 8.3.2 <http://www.codingstandard.com/rule/8-3-2-do-not-write-functions-with-a-high-static-program-path-count/>`_
.. title:: clang-tidy - hicpp-invalid-access-moved
.. meta::
:http-equiv=refresh: 5;URL=bugprone-use-after-move.html
hicpp-invalid-access-moved
==========================
This check is an alias for `bugprone-use-after-move <bugprone-use-after-move.html>`_.
Implements parts of the `rule 8.4.1 <http://www.codingstandard.com/rule/8-4-1-do-not-access-an-invalid-object-or-an-object-with-indeterminate-value/>`_ to check if moved-from objects are accessed.
.. title:: clang-tidy - hicpp-member-init
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-pro-type-member-init.html
hicpp-member-init
=================
This check is an alias for `cppcoreguidelines-pro-type-member-init <cppcoreguidelines-pro-type-member-init.html>`_.
Implements the check for
`rule 12.4.2 <http://www.codingstandard.com/rule/12-4-2-ensure-that-a-constructor-initializes-explicitly-all-base-classes-and-non-static-data-members/>`_
to initialize class members in the right order.
.. title:: clang-tidy - hicpp-move-const-arg
.. meta::
:http-equiv=refresh: 5;URL=performance-move-const-arg.html
hicpp-move-const-arg
====================
The `hicpp-move-const-arg` check is an alias, please see
`performance-move-const-arg <performance-move-const-arg.html>`_ for more information.
It enforces the `rule 17.3.1 <http://www.codingstandard.com/rule/17-3-1-do-not-use-stdmove-on-objects-declared-with-const-or-const-type/>`_.
.. title:: clang-tidy - hicpp-multiway-paths-covered
hicpp-multiway-paths-covered
============================
This check discovers situations where code paths are not fully-covered.
It furthermore suggests using ``if`` instead of ``switch`` if the code will be more clear.
The `rule 6.1.2 <http://www.codingstandard.com/rule/6-1-2-explicitly-cover-all-paths-through-multi-way-selection-statements/>`_
and `rule 6.1.4 <http://www.codingstandard.com/rule/6-1-4-ensure-that-a-switch-statement-has-at-least-two-case-labels-distinct-from-the-default-label/>`_
of the High Integrity C++ Coding Standard are enforced.
``if-else if`` chains that miss a final ``else`` branch might lead to unexpected
program execution and be the result of a logical error.
If the missing ``else`` branch is intended you can leave it empty with a clarifying
comment.
This warning can be noisy on some code bases, so it is disabled by default.
.. code-block:: c++
void f1() {
int i = determineTheNumber();
if(i > 0) {
// Some Calculation
} else if (i < 0) {
// Precondition violated or something else.
}
// ...
}
Similar arguments hold for ``switch`` statements which do not cover all possible code paths.
.. code-block:: c++
// The missing default branch might be a logical error. It can be kept empty
// if there is nothing to do, making it explicit.
void f2(int i) {
switch (i) {
case 0: // something
break;
case 1: // something else
break;
}
// All other numbers?
}
// Violates this rule as well, but already emits a compiler warning (-Wswitch).
enum Color { Red, Green, Blue, Yellow };
void f3(enum Color c) {
switch (c) {
case Red: // We can't drive for now.
break;
case Green: // We are allowed to drive.
break;
}
// Other cases missing
}
The `rule 6.1.4 <http://www.codingstandard.com/rule/6-1-4-ensure-that-a-switch-statement-has-at-least-two-case-labels-distinct-from-the-default-label/>`_
requires every ``switch`` statement to have at least two ``case`` labels other than a `default` label.
Otherwise, the ``switch`` could be better expressed with an ``if`` statement.
Degenerated ``switch`` statements without any labels are caught as well.
.. code-block:: c++
// Degenerated switch that could be better written as `if`
int i = 42;
switch(i) {
case 1: // do something here
default: // do somethe else here
}
// Should rather be the following:
if (i == 1) {
// do something here
}
else {
// do something here
}
.. code-block:: c++
// A completely degenerated switch will be diagnosed.
int i = 42;
switch(i) {}
Options
-------
.. option:: WarnOnMissingElse
Boolean flag that activates a warning for missing ``else`` branches.
Default is `false`.
.. title:: clang-tidy - hicpp-named-parameter
.. meta::
:http-equiv=refresh: 5;URL=readability-named-parameter.html
hicpp-named-parameter
=====================
This check is an alias for `readability-named-parameter <readability-named-parameter.html>`_.
Implements `rule 8.2.1 <http://www.codingstandard.com/rule/8-2-1-make-parameter-names-absent-or-identical-in-all-declarations/>`_.
.. title:: clang-tidy - hicpp-new-delete-operators
.. meta::
:http-equiv=refresh: 5;URL=misc-new-delete-overloads.html
hicpp-new-delete-operators
==========================
This check is an alias for `misc-new-delete-overloads <misc-new-delete-overloads.html>`_.
Implements `rule 12.3.1 <http://www.codingstandard.com/section/12-3-free-store/>`_ to ensure
the `new` and `delete` operators have the correct signature.
.. title:: clang-tidy - hicpp-no-array-decay
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-pro-bounds-array-to-pointer-decay.html
hicpp-no-array-decay
====================
The `hicpp-no-array-decay` check is an alias, please see
`cppcoreguidelines-pro-bounds-array-to-pointer-decay <cppcoreguidelines-pro-bounds-array-to-pointer-decay.html>`_
for more information.
It enforces the `rule 4.1.1 <http://www.codingstandard.com/section/4-1-array-to-pointer-conversion/>`_.
.. title:: clang-tidy - hicpp-no-assembler
hicpp-no-assembler
===================
Check for assembler statements. No fix is offered.
Inline assembler is forbidden by the `High Intergrity C++ Coding Standard
<http://www.codingstandard.com/section/7-5-the-asm-declaration/>`_
as it restricts the portability of code.
.. title:: clang-tidy - hicpp-no-malloc
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-no-malloc.html
hicpp-no-malloc
===============
The `hicpp-no-malloc` check is an alias, please see
`cppcoreguidelines-no-malloc <cppcoreguidelines-no-malloc.html>`_
for more information.
It enforces the `rule 5.3.2 <http://www.codingstandard.com/rule/5-3-2-allocate-memory-using-new-and-release-it-using-delete/>`_.
.. title:: clang-tidy - hicpp-noexcept-move
.. meta::
:http-equiv=refresh: 5;URL=performance-noexcept-move-constructor.html
hicpp-noexcept-move
===================
This check is an alias for `performance-noexcept-move-constructor <performance-noexcept-move-constructor.html>`_.
Checks `rule 12.5.4 <http://www.codingstandard.com/rule/12-5-4-declare-noexcept-the-move-constructor-and-move-assignment-operator>`_ to mark move assignment and move construction `noexcept`.
.. title:: clang-tidy - hicpp-signed-bitwise
hicpp-signed-bitwise
====================
Finds uses of bitwise operations on signed integer types, which may lead to
undefined or implementation defined behaviour.
The according rule is defined in the `High Integrity C++ Standard, Section 5.6.1 <http://www.codingstandard.com/section/5-6-shift-operators/>`_.
Options
-------
.. option:: IgnorePositiveIntegerLiterals
If this option is set to `true`, the check will not warn on bitwise operations with positive integer literals, e.g. `~0`, `2 << 1`, etc.
Default value is `false`.
.. title:: clang-tidy - hicpp-special-member-functions
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-special-member-functions.html
hicpp-special-member-functions
==============================
This check is an alias for `cppcoreguidelines-special-member-functions <cppcoreguidelines-special-member-functions.html>`_.
Checks that special member functions have the correct signature, according to `rule 12.5.7 <http://www.codingstandard.com/rule/12-5-7-declare-assignment-operators-with-the-ref-qualifier/>`_.
.. title:: clang-tidy - hicpp-static-assert
.. meta::
:http-equiv=refresh: 5;URL=misc-static-assert.html
hicpp-static-assert
===================
The `hicpp-static-assert` check is an alias, please see
`misc-static-assert <misc-static-assert.html>`_ for more information.
It enforces the `rule 7.1.10 <http://www.codingstandard.com/rule/6-1-1-enclose-the-body-of-a-selection-or-an-iteration-statement-in-a-compound-statement/>`_.
.. title:: clang-tidy - hicpp-undelegated-constructor
.. meta::
:http-equiv=refresh: 5;URL=bugprone-undelegated-constructor.html
hicpp-undelegated-constructor
=============================
This check is an alias for `bugprone-undelegated-constructor <bugprone-undelegated-constructor.html>`_.
Partially implements `rule 12.4.5 <http://www.codingstandard.com/rule/12-4-5-use-delegating-constructors-to-reduce-code-duplication/>`_
to find misplaced constructor calls inside a constructor.
.. code-block:: c++
struct Ctor {
Ctor();
Ctor(int);
Ctor(int, int);
Ctor(Ctor *i) {
// All Ctor() calls result in a temporary object
Ctor(); // did you intend to call a delegated constructor?
Ctor(0); // did you intend to call a delegated constructor?
Ctor(1, 2); // did you intend to call a delegated constructor?
foo();
}
};
.. title:: clang-tidy - hicpp-uppercase-literal-suffix
.. meta::
:http-equiv=refresh: 5;URL=readability-uppercase-literal-suffix.html
hicpp-uppercase-literal-suffix
==============================
The hicpp-uppercase-literal-suffix check is an alias, please see
`readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_ for more information.
.. title:: clang-tidy - hicpp-use-auto
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-auto.html
hicpp-use-auto
==============
The `hicpp-use-auto` check is an alias, please see
`modernize-use-auto <modernize-use-auto.html>`_ for more information.
It enforces the `rule 7.1.8 <http://www.codingstandard.com/rule/7-1-8-use-auto-id-expr-when-declaring-a-variable-to-have-the-same-type-as-its-initializer-function-call/>`_.
.. title:: clang-tidy - hicpp-use-emplace
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-emplace.html
hicpp-use-emplace
=================
The `hicpp-use-emplace` check is an alias, please see
`modernize-use-emplace <modernize-use-emplace.html>`_ for more information.
It enforces the `rule 17.4.2 <http://www.codingstandard.com/rule/17-4-2-use-api-calls-that-construct-objects-in-place/>`_.
.. title:: clang-tidy - hicpp-use-equals-defaults
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-equals-default.html
hicpp-use-equals-default
========================
This check is an alias for `modernize-use-equals-default <modernize-use-equals-default.html>`_.
Implements `rule 12.5.1 <http://www.codingstandard.com/rule/12-5-1-define-explicitly-default-or-delete-implicit-special-member-functions-of-concrete-classes/>`_ to explicitly default special member functions.
.. title:: clang-tidy - hicpp-use-equals-delete
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-equals-delete.html
hicpp-use-equals-delete
=======================
This check is an alias for `modernize-use-equals-delete <modernize-use-equals-delete.html>`_.
Implements `rule 12.5.1 <http://www.codingstandard.com/rule/12-5-1-define-explicitly-default-or-delete-implicit-special-member-functions-of-concrete-classes/>`_
to explicitly default or delete special member functions.
.. title:: clang-tidy - hicpp-use-noexcept
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-noexcept.html
hicpp-use-noexcept
==================
The `hicpp-use-noexcept` check is an alias, please see
`modernize-use-noexcept <modernize-use-noexcept.html>`_ for more information.
It enforces the `rule 1.3.5 <http://www.codingstandard.com/rule/1-3-5-do-not-use-throw-exception-specifications/>`_.
.. title:: clang-tidy - hicpp-use-nullptr
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-nullptr.html
hicpp-use-nullptr
=================
The `hicpp-use-nullptr` check is an alias, please see
`modernize-use-nullptr <modernize-use-nullptr.html>`_ for more information.
It enforces the `rule 2.5.3 <http://www.codingstandard.com/rule/2-5-3-use-nullptr-for-the-null-pointer-constant/>`_.
.. title:: clang-tidy - hicpp-use-override
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-override.html
hicpp-use-override
==================
This check is an alias for `modernize-use-override <modernize-use-override.html>`_.
Implements `rule 10.2.1 <http://www.codingstandard.com/section/10-2-virtual-functions/>`_ to
declare a virtual function `override` when overriding.
.. title:: clang-tidy - hicpp-vararg
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-pro-type-vararg.html
hicpp-vararg
============
The `hicpp-vararg` check is an alias, please see
`cppcoreguidelines-pro-type-vararg <cppcoreguidelines-pro-type-vararg.html>`_
for more information.
It enforces the `rule 14.1.1 <http://www.codingstandard.com/section/14-1-template-declarations/>`_.
.. title:: clang-tidy - linuxkernel-must-use-errs
linuxkernel-must-use-errs
=========================
Checks Linux kernel code to see if it uses the results from the functions in
``linux/err.h``. Also checks to see if code uses the results from functions that
directly return a value from one of these error functions.
This is important in the Linux kernel because ``ERR_PTR``, ``PTR_ERR``,
``IS_ERR``, ``IS_ERR_OR_NULL``, ``ERR_CAST``, and ``PTR_ERR_OR_ZERO`` return
values must be checked, since positive pointers and negative error codes are
being used in the same context. These functions are marked with
``__attribute__((warn_unused_result))``, but some kernel versions do not have
this warning enabled for clang.
Examples:
.. code-block:: c
/* Trivial unused call to an ERR function */
PTR_ERR_OR_ZERO(some_function_call());
/* A function that returns ERR_PTR. */
void *fn() { ERR_PTR(-EINVAL); }
/* An invalid use of fn. */
fn();
.. title:: clang-tidy - Clang-Tidy Checks
Clang-Tidy Checks
=================
.. toctree::
:glob:
:hidden:
*
.. csv-table::
:header: "Name", "Offers fixes"
`abseil-duration-addition <abseil-duration-addition.html>`_, "Yes"
`abseil-duration-comparison <abseil-duration-comparison.html>`_, "Yes"
`abseil-duration-conversion-cast <abseil-duration-conversion-cast.html>`_, "Yes"
`abseil-duration-division <abseil-duration-division.html>`_, "Yes"
`abseil-duration-factory-float <abseil-duration-factory-float.html>`_, "Yes"
`abseil-duration-factory-scale <abseil-duration-factory-scale.html>`_, "Yes"
`abseil-duration-subtraction <abseil-duration-subtraction.html>`_, "Yes"
`abseil-duration-unnecessary-conversion <abseil-duration-unnecessary-conversion.html>`_, "Yes"
`abseil-faster-strsplit-delimiter <abseil-faster-strsplit-delimiter.html>`_, "Yes"
`abseil-no-internal-dependencies <abseil-no-internal-dependencies.html>`_,
`abseil-no-namespace <abseil-no-namespace.html>`_,
`abseil-redundant-strcat-calls <abseil-redundant-strcat-calls.html>`_, "Yes"
`abseil-str-cat-append <abseil-str-cat-append.html>`_, "Yes"
`abseil-string-find-startswith <abseil-string-find-startswith.html>`_, "Yes"
`abseil-string-find-str-contains <abseil-string-find-str-contains.html>`_, "Yes"
`abseil-time-comparison <abseil-time-comparison.html>`_, "Yes"
`abseil-time-subtraction <abseil-time-subtraction.html>`_, "Yes"
`abseil-upgrade-duration-conversions <abseil-upgrade-duration-conversions.html>`_, "Yes"
`altera-id-dependent-backward-branch <altera-id-dependent-backward-branch.html>`_,
`altera-kernel-name-restriction <altera-kernel-name-restriction.html>`_,
`altera-single-work-item-barrier <altera-single-work-item-barrier.html>`_,
`altera-struct-pack-align <altera-struct-pack-align.html>`_, "Yes"
`altera-unroll-loops <altera-unroll-loops.html>`_,
`android-cloexec-accept <android-cloexec-accept.html>`_, "Yes"
`android-cloexec-accept4 <android-cloexec-accept4.html>`_,
`android-cloexec-creat <android-cloexec-creat.html>`_, "Yes"
`android-cloexec-dup <android-cloexec-dup.html>`_, "Yes"
`android-cloexec-epoll-create <android-cloexec-epoll-create.html>`_,
`android-cloexec-epoll-create1 <android-cloexec-epoll-create1.html>`_,
`android-cloexec-fopen <android-cloexec-fopen.html>`_,
`android-cloexec-inotify-init <android-cloexec-inotify-init.html>`_,
`android-cloexec-inotify-init1 <android-cloexec-inotify-init1.html>`_,
`android-cloexec-memfd-create <android-cloexec-memfd-create.html>`_,
`android-cloexec-open <android-cloexec-open.html>`_,
`android-cloexec-pipe <android-cloexec-pipe.html>`_, "Yes"
`android-cloexec-pipe2 <android-cloexec-pipe2.html>`_,
`android-cloexec-socket <android-cloexec-socket.html>`_,
`android-comparison-in-temp-failure-retry <android-comparison-in-temp-failure-retry.html>`_,
`boost-use-to-string <boost-use-to-string.html>`_, "Yes"
`bugprone-argument-comment <bugprone-argument-comment.html>`_, "Yes"
`bugprone-assert-side-effect <bugprone-assert-side-effect.html>`_,
`bugprone-bad-signal-to-kill-thread <bugprone-bad-signal-to-kill-thread.html>`_,
`bugprone-bool-pointer-implicit-conversion <bugprone-bool-pointer-implicit-conversion.html>`_, "Yes"
`bugprone-branch-clone <bugprone-branch-clone.html>`_,
`bugprone-copy-constructor-init <bugprone-copy-constructor-init.html>`_, "Yes"
`bugprone-dangling-handle <bugprone-dangling-handle.html>`_,
`bugprone-dynamic-static-initializers <bugprone-dynamic-static-initializers.html>`_,
`bugprone-exception-escape <bugprone-exception-escape.html>`_,
`bugprone-fold-init-type <bugprone-fold-init-type.html>`_,
`bugprone-forward-declaration-namespace <bugprone-forward-declaration-namespace.html>`_,
`bugprone-forwarding-reference-overload <bugprone-forwarding-reference-overload.html>`_,
`bugprone-implicit-widening-of-multiplication-result <bugprone-implicit-widening-of-multiplication-result.html>`_, "Yes"
`bugprone-inaccurate-erase <bugprone-inaccurate-erase.html>`_, "Yes"
`bugprone-incorrect-roundings <bugprone-incorrect-roundings.html>`_,
`bugprone-infinite-loop <bugprone-infinite-loop.html>`_,
`bugprone-integer-division <bugprone-integer-division.html>`_,
`bugprone-lambda-function-name <bugprone-lambda-function-name.html>`_,
`bugprone-macro-parentheses <bugprone-macro-parentheses.html>`_, "Yes"
`bugprone-macro-repeated-side-effects <bugprone-macro-repeated-side-effects.html>`_,
`bugprone-misplaced-operator-in-strlen-in-alloc <bugprone-misplaced-operator-in-strlen-in-alloc.html>`_, "Yes"
`bugprone-misplaced-pointer-arithmetic-in-alloc <bugprone-misplaced-pointer-arithmetic-in-alloc.html>`_, "Yes"
`bugprone-misplaced-widening-cast <bugprone-misplaced-widening-cast.html>`_,
`bugprone-move-forwarding-reference <bugprone-move-forwarding-reference.html>`_, "Yes"
`bugprone-multiple-statement-macro <bugprone-multiple-statement-macro.html>`_,
`bugprone-no-escape <bugprone-no-escape.html>`_,
`bugprone-not-null-terminated-result <bugprone-not-null-terminated-result.html>`_, "Yes"
`bugprone-parent-virtual-call <bugprone-parent-virtual-call.html>`_, "Yes"
`bugprone-posix-return <bugprone-posix-return.html>`_, "Yes"
`bugprone-redundant-branch-condition <bugprone-redundant-branch-condition.html>`_, "Yes"
`bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_, "Yes"
`bugprone-signal-handler <bugprone-signal-handler.html>`_,
`bugprone-signed-char-misuse <bugprone-signed-char-misuse.html>`_,
`bugprone-sizeof-container <bugprone-sizeof-container.html>`_,
`bugprone-sizeof-expression <bugprone-sizeof-expression.html>`_,
`bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_,
`bugprone-string-constructor <bugprone-string-constructor.html>`_, "Yes"
`bugprone-string-integer-assignment <bugprone-string-integer-assignment.html>`_, "Yes"
`bugprone-string-literal-with-embedded-nul <bugprone-string-literal-with-embedded-nul.html>`_,
`bugprone-suspicious-enum-usage <bugprone-suspicious-enum-usage.html>`_,
`bugprone-suspicious-include <bugprone-suspicious-include.html>`_,
`bugprone-suspicious-memset-usage <bugprone-suspicious-memset-usage.html>`_, "Yes"
`bugprone-suspicious-missing-comma <bugprone-suspicious-missing-comma.html>`_,
`bugprone-suspicious-semicolon <bugprone-suspicious-semicolon.html>`_, "Yes"
`bugprone-suspicious-string-compare <bugprone-suspicious-string-compare.html>`_, "Yes"
`bugprone-swapped-arguments <bugprone-swapped-arguments.html>`_, "Yes"
`bugprone-terminating-continue <bugprone-terminating-continue.html>`_, "Yes"
`bugprone-throw-keyword-missing <bugprone-throw-keyword-missing.html>`_,
`bugprone-too-small-loop-variable <bugprone-too-small-loop-variable.html>`_,
`bugprone-undefined-memory-manipulation <bugprone-undefined-memory-manipulation.html>`_,
`bugprone-undelegated-constructor <bugprone-undelegated-constructor.html>`_,
`bugprone-unhandled-exception-at-new <bugprone-unhandled-exception-at-new.html>`_,
`bugprone-unhandled-self-assignment <bugprone-unhandled-self-assignment.html>`_,
`bugprone-unused-raii <bugprone-unused-raii.html>`_, "Yes"
`bugprone-unused-return-value <bugprone-unused-return-value.html>`_,
`bugprone-use-after-move <bugprone-use-after-move.html>`_,
`bugprone-virtual-near-miss <bugprone-virtual-near-miss.html>`_, "Yes"
`cert-dcl21-cpp <cert-dcl21-cpp.html>`_,
`cert-dcl50-cpp <cert-dcl50-cpp.html>`_,
`cert-dcl58-cpp <cert-dcl58-cpp.html>`_,
`cert-env33-c <cert-env33-c.html>`_,
`cert-err34-c <cert-err34-c.html>`_,
`cert-err52-cpp <cert-err52-cpp.html>`_,
`cert-err58-cpp <cert-err58-cpp.html>`_,
`cert-err60-cpp <cert-err60-cpp.html>`_,
`cert-flp30-c <cert-flp30-c.html>`_,
`cert-mem57-cpp <cert-mem57-cpp.html>`_,
`cert-msc50-cpp <cert-msc50-cpp.html>`_,
`cert-msc51-cpp <cert-msc51-cpp.html>`_,
`cert-oop57-cpp <cert-oop57-cpp.html>`_,
`cert-oop58-cpp <cert-oop58-cpp.html>`_,
`clang-analyzer-core.DynamicTypePropagation <clang-analyzer-core.DynamicTypePropagation.html>`_,
`clang-analyzer-core.uninitialized.CapturedBlockVariable <clang-analyzer-core.uninitialized.CapturedBlockVariable.html>`_,
`clang-analyzer-cplusplus.InnerPointer <clang-analyzer-cplusplus.InnerPointer.html>`_,
`clang-analyzer-nullability.NullableReturnedFromNonnull <clang-analyzer-nullability.NullableReturnedFromNonnull.html>`_,
`clang-analyzer-optin.osx.OSObjectCStyleCast <clang-analyzer-optin.osx.OSObjectCStyleCast.html>`_,
`clang-analyzer-optin.performance.GCDAntipattern <clang-analyzer-optin.performance.GCDAntipattern.html>`_,
`clang-analyzer-optin.performance.Padding <clang-analyzer-optin.performance.Padding.html>`_,
`clang-analyzer-optin.portability.UnixAPI <clang-analyzer-optin.portability.UnixAPI.html>`_,
`clang-analyzer-osx.MIG <clang-analyzer-osx.MIG.html>`_,
`clang-analyzer-osx.NumberObjectConversion <clang-analyzer-osx.NumberObjectConversion.html>`_,
`clang-analyzer-osx.OSObjectRetainCount <clang-analyzer-osx.OSObjectRetainCount.html>`_,
`clang-analyzer-osx.ObjCProperty <clang-analyzer-osx.ObjCProperty.html>`_,
`clang-analyzer-osx.cocoa.AutoreleaseWrite <clang-analyzer-osx.cocoa.AutoreleaseWrite.html>`_,
`clang-analyzer-osx.cocoa.Loops <clang-analyzer-osx.cocoa.Loops.html>`_,
`clang-analyzer-osx.cocoa.MissingSuperCall <clang-analyzer-osx.cocoa.MissingSuperCall.html>`_,
`clang-analyzer-osx.cocoa.NonNilReturnValue <clang-analyzer-osx.cocoa.NonNilReturnValue.html>`_,
`clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak <clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak.html>`_,
`clang-analyzer-valist.CopyToSelf <clang-analyzer-valist.CopyToSelf.html>`_,
`clang-analyzer-valist.Uninitialized <clang-analyzer-valist.Uninitialized.html>`_,
`clang-analyzer-valist.Unterminated <clang-analyzer-valist.Unterminated.html>`_,
`concurrency-mt-unsafe <concurrency-mt-unsafe.html>`_,
`concurrency-thread-canceltype-asynchronous <concurrency-thread-canceltype-asynchronous.html>`_,
`cppcoreguidelines-avoid-goto <cppcoreguidelines-avoid-goto.html>`_,
`cppcoreguidelines-avoid-non-const-global-variables <cppcoreguidelines-avoid-non-const-global-variables.html>`_,
`cppcoreguidelines-init-variables <cppcoreguidelines-init-variables.html>`_, "Yes"
`cppcoreguidelines-interfaces-global-init <cppcoreguidelines-interfaces-global-init.html>`_,
`cppcoreguidelines-macro-usage <cppcoreguidelines-macro-usage.html>`_,
`cppcoreguidelines-narrowing-conversions <cppcoreguidelines-narrowing-conversions.html>`_,
`cppcoreguidelines-no-malloc <cppcoreguidelines-no-malloc.html>`_,
`cppcoreguidelines-owning-memory <cppcoreguidelines-owning-memory.html>`_,
`cppcoreguidelines-prefer-member-initializer <cppcoreguidelines-prefer-member-initializer.html>`_, "Yes"
`cppcoreguidelines-pro-bounds-array-to-pointer-decay <cppcoreguidelines-pro-bounds-array-to-pointer-decay.html>`_,
`cppcoreguidelines-pro-bounds-constant-array-index <cppcoreguidelines-pro-bounds-constant-array-index.html>`_, "Yes"
`cppcoreguidelines-pro-bounds-pointer-arithmetic <cppcoreguidelines-pro-bounds-pointer-arithmetic.html>`_,
`cppcoreguidelines-pro-type-const-cast <cppcoreguidelines-pro-type-const-cast.html>`_,
`cppcoreguidelines-pro-type-cstyle-cast <cppcoreguidelines-pro-type-cstyle-cast.html>`_, "Yes"
`cppcoreguidelines-pro-type-member-init <cppcoreguidelines-pro-type-member-init.html>`_, "Yes"
`cppcoreguidelines-pro-type-reinterpret-cast <cppcoreguidelines-pro-type-reinterpret-cast.html>`_,
`cppcoreguidelines-pro-type-static-cast-downcast <cppcoreguidelines-pro-type-static-cast-downcast.html>`_, "Yes"
`cppcoreguidelines-pro-type-union-access <cppcoreguidelines-pro-type-union-access.html>`_,
`cppcoreguidelines-pro-type-vararg <cppcoreguidelines-pro-type-vararg.html>`_,
`cppcoreguidelines-slicing <cppcoreguidelines-slicing.html>`_,
`cppcoreguidelines-special-member-functions <cppcoreguidelines-special-member-functions.html>`_,
`darwin-avoid-spinlock <darwin-avoid-spinlock.html>`_,
`darwin-dispatch-once-nonstatic <darwin-dispatch-once-nonstatic.html>`_, "Yes"
`fuchsia-default-arguments-calls <fuchsia-default-arguments-calls.html>`_,
`fuchsia-default-arguments-declarations <fuchsia-default-arguments-declarations.html>`_, "Yes"
`fuchsia-multiple-inheritance <fuchsia-multiple-inheritance.html>`_,
`fuchsia-overloaded-operator <fuchsia-overloaded-operator.html>`_,
`fuchsia-statically-constructed-objects <fuchsia-statically-constructed-objects.html>`_,
`fuchsia-trailing-return <fuchsia-trailing-return.html>`_,
`fuchsia-virtual-inheritance <fuchsia-virtual-inheritance.html>`_,
`google-build-explicit-make-pair <google-build-explicit-make-pair.html>`_,
`google-build-namespaces <google-build-namespaces.html>`_,
`google-build-using-namespace <google-build-using-namespace.html>`_,
`google-default-arguments <google-default-arguments.html>`_,
`google-explicit-constructor <google-explicit-constructor.html>`_, "Yes"
`google-global-names-in-headers <google-global-names-in-headers.html>`_,
`google-objc-avoid-nsobject-new <google-objc-avoid-nsobject-new.html>`_,
`google-objc-avoid-throwing-exception <google-objc-avoid-throwing-exception.html>`_,
`google-objc-function-naming <google-objc-function-naming.html>`_,
`google-objc-global-variable-declaration <google-objc-global-variable-declaration.html>`_,
`google-readability-avoid-underscore-in-googletest-name <google-readability-avoid-underscore-in-googletest-name.html>`_,
`google-readability-casting <google-readability-casting.html>`_,
`google-readability-todo <google-readability-todo.html>`_,
`google-runtime-int <google-runtime-int.html>`_,
`google-runtime-operator <google-runtime-operator.html>`_,
`google-upgrade-googletest-case <google-upgrade-googletest-case.html>`_, "Yes"
`hicpp-avoid-goto <hicpp-avoid-goto.html>`_,
`hicpp-exception-baseclass <hicpp-exception-baseclass.html>`_,
`hicpp-multiway-paths-covered <hicpp-multiway-paths-covered.html>`_,
`hicpp-no-assembler <hicpp-no-assembler.html>`_,
`hicpp-signed-bitwise <hicpp-signed-bitwise.html>`_,
`linuxkernel-must-use-errs <linuxkernel-must-use-errs.html>`_,
`llvm-header-guard <llvm-header-guard.html>`_,
`llvm-include-order <llvm-include-order.html>`_, "Yes"
`llvm-namespace-comment <llvm-namespace-comment.html>`_,
`llvm-prefer-isa-or-dyn-cast-in-conditionals <llvm-prefer-isa-or-dyn-cast-in-conditionals.html>`_, "Yes"
`llvm-prefer-register-over-unsigned <llvm-prefer-register-over-unsigned.html>`_, "Yes"
`llvm-twine-local <llvm-twine-local.html>`_, "Yes"
`llvmlibc-callee-namespace <llvmlibc-callee-namespace.html>`_,
`llvmlibc-implementation-in-namespace <llvmlibc-implementation-in-namespace.html>`_,
`llvmlibc-restrict-system-libc-headers <llvmlibc-restrict-system-libc-headers.html>`_, "Yes"
`misc-definitions-in-headers <misc-definitions-in-headers.html>`_, "Yes"
`misc-misplaced-const <misc-misplaced-const.html>`_,
`misc-new-delete-overloads <misc-new-delete-overloads.html>`_,
`misc-no-recursion <misc-no-recursion.html>`_,
`misc-non-copyable-objects <misc-non-copyable-objects.html>`_,
`misc-non-private-member-variables-in-classes <misc-non-private-member-variables-in-classes.html>`_,
`misc-redundant-expression <misc-redundant-expression.html>`_, "Yes"
`misc-static-assert <misc-static-assert.html>`_, "Yes"
`misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_,
`misc-unconventional-assign-operator <misc-unconventional-assign-operator.html>`_,
`misc-uniqueptr-reset-release <misc-uniqueptr-reset-release.html>`_, "Yes"
`misc-unused-alias-decls <misc-unused-alias-decls.html>`_, "Yes"
`misc-unused-parameters <misc-unused-parameters.html>`_, "Yes"
`misc-unused-using-decls <misc-unused-using-decls.html>`_, "Yes"
`modernize-avoid-bind <modernize-avoid-bind.html>`_, "Yes"
`modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_,
`modernize-concat-nested-namespaces <modernize-concat-nested-namespaces.html>`_, "Yes"
`modernize-deprecated-headers <modernize-deprecated-headers.html>`_, "Yes"
`modernize-deprecated-ios-base-aliases <modernize-deprecated-ios-base-aliases.html>`_, "Yes"
`modernize-loop-convert <modernize-loop-convert.html>`_, "Yes"
`modernize-make-shared <modernize-make-shared.html>`_, "Yes"
`modernize-make-unique <modernize-make-unique.html>`_, "Yes"
`modernize-pass-by-value <modernize-pass-by-value.html>`_, "Yes"
`modernize-raw-string-literal <modernize-raw-string-literal.html>`_, "Yes"
`modernize-redundant-void-arg <modernize-redundant-void-arg.html>`_, "Yes"
`modernize-replace-auto-ptr <modernize-replace-auto-ptr.html>`_, "Yes"
`modernize-replace-disallow-copy-and-assign-macro <modernize-replace-disallow-copy-and-assign-macro.html>`_, "Yes"
`modernize-replace-random-shuffle <modernize-replace-random-shuffle.html>`_, "Yes"
`modernize-return-braced-init-list <modernize-return-braced-init-list.html>`_, "Yes"
`modernize-shrink-to-fit <modernize-shrink-to-fit.html>`_, "Yes"
`modernize-unary-static-assert <modernize-unary-static-assert.html>`_, "Yes"
`modernize-use-auto <modernize-use-auto.html>`_, "Yes"
`modernize-use-bool-literals <modernize-use-bool-literals.html>`_, "Yes"
`modernize-use-default-member-init <modernize-use-default-member-init.html>`_, "Yes"
`modernize-use-emplace <modernize-use-emplace.html>`_, "Yes"
`modernize-use-equals-default <modernize-use-equals-default.html>`_, "Yes"
`modernize-use-equals-delete <modernize-use-equals-delete.html>`_, "Yes"
`modernize-use-nodiscard <modernize-use-nodiscard.html>`_, "Yes"
`modernize-use-noexcept <modernize-use-noexcept.html>`_, "Yes"
`modernize-use-nullptr <modernize-use-nullptr.html>`_, "Yes"
`modernize-use-override <modernize-use-override.html>`_, "Yes"
`modernize-use-trailing-return-type <modernize-use-trailing-return-type.html>`_, "Yes"
`modernize-use-transparent-functors <modernize-use-transparent-functors.html>`_, "Yes"
`modernize-use-uncaught-exceptions <modernize-use-uncaught-exceptions.html>`_, "Yes"
`modernize-use-using <modernize-use-using.html>`_, "Yes"
`mpi-buffer-deref <mpi-buffer-deref.html>`_, "Yes"
`mpi-type-mismatch <mpi-type-mismatch.html>`_, "Yes"
`objc-avoid-nserror-init <objc-avoid-nserror-init.html>`_,
`objc-dealloc-in-category <objc-dealloc-in-category.html>`_,
`objc-forbidden-subclassing <objc-forbidden-subclassing.html>`_,
`objc-missing-hash <objc-missing-hash.html>`_,
`objc-nsinvocation-argument-lifetime <objc-nsinvocation-argument-lifetime.html>`_, "Yes"
`objc-property-declaration <objc-property-declaration.html>`_, "Yes"
`objc-super-self <objc-super-self.html>`_, "Yes"
`openmp-exception-escape <openmp-exception-escape.html>`_,
`openmp-use-default-none <openmp-use-default-none.html>`_,
`performance-faster-string-find <performance-faster-string-find.html>`_, "Yes"
`performance-for-range-copy <performance-for-range-copy.html>`_, "Yes"
`performance-implicit-conversion-in-loop <performance-implicit-conversion-in-loop.html>`_,
`performance-inefficient-algorithm <performance-inefficient-algorithm.html>`_, "Yes"
`performance-inefficient-string-concatenation <performance-inefficient-string-concatenation.html>`_,
`performance-inefficient-vector-operation <performance-inefficient-vector-operation.html>`_, "Yes"
`performance-move-const-arg <performance-move-const-arg.html>`_, "Yes"
`performance-move-constructor-init <performance-move-constructor-init.html>`_,
`performance-no-automatic-move <performance-no-automatic-move.html>`_,
`performance-no-int-to-ptr <performance-no-int-to-ptr.html>`_,
`performance-noexcept-move-constructor <performance-noexcept-move-constructor.html>`_, "Yes"
`performance-trivially-destructible <performance-trivially-destructible.html>`_, "Yes"
`performance-type-promotion-in-math-fn <performance-type-promotion-in-math-fn.html>`_, "Yes"
`performance-unnecessary-copy-initialization <performance-unnecessary-copy-initialization.html>`_,
`performance-unnecessary-value-param <performance-unnecessary-value-param.html>`_, "Yes"
`portability-restrict-system-includes <portability-restrict-system-includes.html>`_, "Yes"
`portability-simd-intrinsics <portability-simd-intrinsics.html>`_,
`readability-avoid-const-params-in-decls <readability-avoid-const-params-in-decls.html>`_,
`readability-braces-around-statements <readability-braces-around-statements.html>`_, "Yes"
`readability-const-return-type <readability-const-return-type.html>`_, "Yes"
`readability-container-size-empty <readability-container-size-empty.html>`_, "Yes"
`readability-convert-member-functions-to-static <readability-convert-member-functions-to-static.html>`_,
`readability-delete-null-pointer <readability-delete-null-pointer.html>`_, "Yes"
`readability-else-after-return <readability-else-after-return.html>`_, "Yes"
`readability-function-cognitive-complexity <readability-function-cognitive-complexity.html>`_,
`readability-function-size <readability-function-size.html>`_,
`readability-identifier-naming <readability-identifier-naming.html>`_, "Yes"
`readability-implicit-bool-conversion <readability-implicit-bool-conversion.html>`_, "Yes"
`readability-inconsistent-declaration-parameter-name <readability-inconsistent-declaration-parameter-name.html>`_, "Yes"
`readability-isolate-declaration <readability-isolate-declaration.html>`_, "Yes"
`readability-magic-numbers <readability-magic-numbers.html>`_,
`readability-make-member-function-const <readability-make-member-function-const.html>`_, "Yes"
`readability-misleading-indentation <readability-misleading-indentation.html>`_,
`readability-misplaced-array-index <readability-misplaced-array-index.html>`_, "Yes"
`readability-named-parameter <readability-named-parameter.html>`_, "Yes"
`readability-non-const-parameter <readability-non-const-parameter.html>`_, "Yes"
`readability-qualified-auto <readability-qualified-auto.html>`_, "Yes"
`readability-redundant-access-specifiers <readability-redundant-access-specifiers.html>`_, "Yes"
`readability-redundant-control-flow <readability-redundant-control-flow.html>`_, "Yes"
`readability-redundant-declaration <readability-redundant-declaration.html>`_, "Yes"
`readability-redundant-function-ptr-dereference <readability-redundant-function-ptr-dereference.html>`_, "Yes"
`readability-redundant-member-init <readability-redundant-member-init.html>`_, "Yes"
`readability-redundant-preprocessor <readability-redundant-preprocessor.html>`_,
`readability-redundant-smartptr-get <readability-redundant-smartptr-get.html>`_, "Yes"
`readability-redundant-string-cstr <readability-redundant-string-cstr.html>`_, "Yes"
`readability-redundant-string-init <readability-redundant-string-init.html>`_, "Yes"
`readability-simplify-boolean-expr <readability-simplify-boolean-expr.html>`_, "Yes"
`readability-simplify-subscript-expr <readability-simplify-subscript-expr.html>`_, "Yes"
`readability-static-accessed-through-instance <readability-static-accessed-through-instance.html>`_, "Yes"
`readability-static-definition-in-anonymous-namespace <readability-static-definition-in-anonymous-namespace.html>`_, "Yes"
`readability-string-compare <readability-string-compare.html>`_, "Yes"
`readability-uniqueptr-delete-release <readability-uniqueptr-delete-release.html>`_, "Yes"
`readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_, "Yes"
`readability-use-anyofallof <readability-use-anyofallof.html>`_,
`zircon-temporary-objects <zircon-temporary-objects.html>`_,
.. csv-table:: Aliases..
:header: "Name", "Redirect", "Offers fixes"
`cert-con36-c <cert-con36-c.html>`_, `bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_,
`cert-con54-cpp <cert-con54-cpp.html>`_, `bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_,
`cert-dcl03-c <cert-dcl03-c.html>`_, `misc-static-assert <misc-static-assert.html>`_, "Yes"
`cert-dcl16-c <cert-dcl16-c.html>`_, `readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_, "Yes"
`cert-dcl37-c <cert-dcl37-c.html>`_, `bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_, "Yes"
`cert-dcl51-cpp <cert-dcl51-cpp.html>`_, `bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_, "Yes"
`cert-dcl54-cpp <cert-dcl54-cpp.html>`_, `misc-new-delete-overloads <misc-new-delete-overloads.html>`_,
`cert-dcl59-cpp <cert-dcl59-cpp.html>`_, `google-build-namespaces <google-build-namespaces.html>`_,
`cert-err09-cpp <cert-err09-cpp.html>`_, `misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_,
`cert-err61-cpp <cert-err61-cpp.html>`_, `misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_,
`cert-fio38-c <cert-fio38-c.html>`_, `misc-non-copyable-objects <misc-non-copyable-objects.html>`_,
`cert-msc30-c <cert-msc30-c.html>`_, `cert-msc50-cpp <cert-msc50-cpp.html>`_,
`cert-msc32-c <cert-msc32-c.html>`_, `cert-msc51-cpp <cert-msc51-cpp.html>`_,
`cert-oop11-cpp <cert-oop11-cpp.html>`_, `performance-move-constructor-init <performance-move-constructor-init.html>`_,
`cert-oop54-cpp <cert-oop54-cpp.html>`_, `bugprone-unhandled-self-assignment <bugprone-unhandled-self-assignment.html>`_,
`cert-pos44-c <cert-pos44-c.html>`_, `bugprone-bad-signal-to-kill-thread <bugprone-bad-signal-to-kill-thread.html>`_,
`cert-pos47-c <cert-pos47-c.html>`_, `concurrency-thread-canceltype-asynchronous <concurrency-thread-canceltype-asynchronous.html>`_,
`cert-sig30-c <cert-sig30-c.html>`_, `bugprone-signal-handler <bugprone-signal-handler.html>`_,
`cert-str34-c <cert-str34-c.html>`_, `bugprone-signed-char-misuse <bugprone-signed-char-misuse.html>`_,
`clang-analyzer-core.CallAndMessage <clang-analyzer-core.CallAndMessage.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.DivideZero <clang-analyzer-core.DivideZero.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.NonNullParamChecker <clang-analyzer-core.NonNullParamChecker.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.NullDereference <clang-analyzer-core.NullDereference.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.StackAddressEscape <clang-analyzer-core.StackAddressEscape.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.UndefinedBinaryOperatorResult <clang-analyzer-core.UndefinedBinaryOperatorResult.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.VLASize <clang-analyzer-core.VLASize.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.uninitialized.ArraySubscript <clang-analyzer-core.uninitialized.ArraySubscript.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.uninitialized.Assign <clang-analyzer-core.uninitialized.Assign.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.uninitialized.Branch <clang-analyzer-core.uninitialized.Branch.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.uninitialized.UndefReturn <clang-analyzer-core.uninitialized.UndefReturn.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-cplusplus.Move <clang-analyzer-cplusplus.Move.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-cplusplus.NewDelete <clang-analyzer-cplusplus.NewDelete.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-cplusplus.NewDeleteLeaks <clang-analyzer-cplusplus.NewDeleteLeaks.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-deadcode.DeadStores <clang-analyzer-deadcode.DeadStores.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-nullability.NullPassedToNonnull <clang-analyzer-nullability.NullPassedToNonnull.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-nullability.NullReturnedFromNonnull <clang-analyzer-nullability.NullReturnedFromNonnull.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-nullability.NullableDereferenced <clang-analyzer-nullability.NullableDereferenced.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-nullability.NullablePassedToNonnull <clang-analyzer-nullability.NullablePassedToNonnull.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.cplusplus.UninitializedObject <clang-analyzer-optin.cplusplus.UninitializedObject.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.cplusplus.VirtualCall <clang-analyzer-optin.cplusplus.VirtualCall.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.mpi.MPI-Checker <clang-analyzer-optin.mpi.MPI-Checker.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker <clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker <clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.API <clang-analyzer-osx.API.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.SecKeychainAPI <clang-analyzer-osx.SecKeychainAPI.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.AtSync <clang-analyzer-osx.cocoa.AtSync.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.ClassRelease <clang-analyzer-osx.cocoa.ClassRelease.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.Dealloc <clang-analyzer-osx.cocoa.Dealloc.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.IncompatibleMethodTypes <clang-analyzer-osx.cocoa.IncompatibleMethodTypes.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.NSAutoreleasePool <clang-analyzer-osx.cocoa.NSAutoreleasePool.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.NSError <clang-analyzer-osx.cocoa.NSError.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.NilArg <clang-analyzer-osx.cocoa.NilArg.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.ObjCGenerics <clang-analyzer-osx.cocoa.ObjCGenerics.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.RetainCount <clang-analyzer-osx.cocoa.RetainCount.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.SelfInit <clang-analyzer-osx.cocoa.SelfInit.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.SuperDealloc <clang-analyzer-osx.cocoa.SuperDealloc.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.UnusedIvars <clang-analyzer-osx.cocoa.UnusedIvars.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.VariadicMethodTypes <clang-analyzer-osx.cocoa.VariadicMethodTypes.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.CFError <clang-analyzer-osx.coreFoundation.CFError.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.CFNumber <clang-analyzer-osx.coreFoundation.CFNumber.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.CFRetainRelease <clang-analyzer-osx.coreFoundation.CFRetainRelease.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.containers.OutOfBounds <clang-analyzer-osx.coreFoundation.containers.OutOfBounds.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.containers.PointerSizedValues <clang-analyzer-osx.coreFoundation.containers.PointerSizedValues.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.FloatLoopCounter <clang-analyzer-security.FloatLoopCounter.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling <clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.UncheckedReturn <clang-analyzer-security.insecureAPI.UncheckedReturn.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.bcmp <clang-analyzer-security.insecureAPI.bcmp.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.bcopy <clang-analyzer-security.insecureAPI.bcopy.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.bzero <clang-analyzer-security.insecureAPI.bzero.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.getpw <clang-analyzer-security.insecureAPI.getpw.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.gets <clang-analyzer-security.insecureAPI.gets.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.mkstemp <clang-analyzer-security.insecureAPI.mkstemp.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.mktemp <clang-analyzer-security.insecureAPI.mktemp.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.rand <clang-analyzer-security.insecureAPI.rand.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.strcpy <clang-analyzer-security.insecureAPI.strcpy.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.vfork <clang-analyzer-security.insecureAPI.vfork.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.API <clang-analyzer-unix.API.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.Malloc <clang-analyzer-unix.Malloc.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.MallocSizeof <clang-analyzer-unix.MallocSizeof.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.MismatchedDeallocator <clang-analyzer-unix.MismatchedDeallocator.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.Vfork <clang-analyzer-unix.Vfork.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.cstring.BadSizeArg <clang-analyzer-unix.cstring.BadSizeArg.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.cstring.NullArg <clang-analyzer-unix.cstring.NullArg.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`cppcoreguidelines-avoid-c-arrays <cppcoreguidelines-avoid-c-arrays.html>`_, `modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_,
`cppcoreguidelines-avoid-magic-numbers <cppcoreguidelines-avoid-magic-numbers.html>`_, `readability-magic-numbers <readability-magic-numbers.html>`_,
`cppcoreguidelines-c-copy-assignment-signature <cppcoreguidelines-c-copy-assignment-signature.html>`_, `misc-unconventional-assign-operator <misc-unconventional-assign-operator.html>`_,
`cppcoreguidelines-explicit-virtual-functions <cppcoreguidelines-explicit-virtual-functions.html>`_, `modernize-use-override <modernize-use-override.html>`_, "Yes"
`cppcoreguidelines-non-private-member-variables-in-classes <cppcoreguidelines-non-private-member-variables-in-classes.html>`_, `misc-non-private-member-variables-in-classes <misc-non-private-member-variables-in-classes.html>`_,
`fuchsia-header-anon-namespaces <fuchsia-header-anon-namespaces.html>`_, `google-build-namespaces <google-build-namespaces.html>`_,
`google-readability-braces-around-statements <google-readability-braces-around-statements.html>`_, `readability-braces-around-statements <readability-braces-around-statements.html>`_, "Yes"
`google-readability-function-size <google-readability-function-size.html>`_, `readability-function-size <readability-function-size.html>`_,
`google-readability-namespace-comments <google-readability-namespace-comments.html>`_, `llvm-namespace-comment <llvm-namespace-comment.html>`_,
`hicpp-avoid-c-arrays <hicpp-avoid-c-arrays.html>`_, `modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_,
`hicpp-braces-around-statements <hicpp-braces-around-statements.html>`_, `readability-braces-around-statements <readability-braces-around-statements.html>`_, "Yes"
`hicpp-deprecated-headers <hicpp-deprecated-headers.html>`_, `modernize-deprecated-headers <modernize-deprecated-headers.html>`_, "Yes"
`hicpp-explicit-conversions <hicpp-explicit-conversions.html>`_, `google-explicit-constructor <google-explicit-constructor.html>`_, "Yes"
`hicpp-function-size <hicpp-function-size.html>`_, `readability-function-size <readability-function-size.html>`_,
`hicpp-invalid-access-moved <hicpp-invalid-access-moved.html>`_, `bugprone-use-after-move <bugprone-use-after-move.html>`_,
`hicpp-member-init <hicpp-member-init.html>`_, `cppcoreguidelines-pro-type-member-init <cppcoreguidelines-pro-type-member-init.html>`_, "Yes"
`hicpp-move-const-arg <hicpp-move-const-arg.html>`_, `performance-move-const-arg <performance-move-const-arg.html>`_, "Yes"
`hicpp-named-parameter <hicpp-named-parameter.html>`_, `readability-named-parameter <readability-named-parameter.html>`_, "Yes"
`hicpp-new-delete-operators <hicpp-new-delete-operators.html>`_, `misc-new-delete-overloads <misc-new-delete-overloads.html>`_,
`hicpp-no-array-decay <hicpp-no-array-decay.html>`_, `cppcoreguidelines-pro-bounds-array-to-pointer-decay <cppcoreguidelines-pro-bounds-array-to-pointer-decay.html>`_,
`hicpp-no-malloc <hicpp-no-malloc.html>`_, `cppcoreguidelines-no-malloc <cppcoreguidelines-no-malloc.html>`_,
`hicpp-noexcept-move <hicpp-noexcept-move.html>`_, `performance-noexcept-move-constructor <performance-noexcept-move-constructor.html>`_, "Yes"
`hicpp-special-member-functions <hicpp-special-member-functions.html>`_, `cppcoreguidelines-special-member-functions <cppcoreguidelines-special-member-functions.html>`_,
`hicpp-static-assert <hicpp-static-assert.html>`_, `misc-static-assert <misc-static-assert.html>`_, "Yes"
`hicpp-undelegated-constructor <hicpp-undelegated-constructor.html>`_, `bugprone-undelegated-constructor <bugprone-undelegated-constructor.html>`_,
`hicpp-uppercase-literal-suffix <hicpp-uppercase-literal-suffix.html>`_, `readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_, "Yes"
`hicpp-use-auto <hicpp-use-auto.html>`_, `modernize-use-auto <modernize-use-auto.html>`_, "Yes"
`hicpp-use-emplace <hicpp-use-emplace.html>`_, `modernize-use-emplace <modernize-use-emplace.html>`_, "Yes"
`hicpp-use-equals-default <hicpp-use-equals-default.html>`_, `modernize-use-equals-default <modernize-use-equals-default.html>`_, "Yes"
`hicpp-use-equals-delete <hicpp-use-equals-delete.html>`_, `modernize-use-equals-delete <modernize-use-equals-delete.html>`_, "Yes"
`hicpp-use-noexcept <hicpp-use-noexcept.html>`_, `modernize-use-noexcept <modernize-use-noexcept.html>`_, "Yes"
`hicpp-use-nullptr <hicpp-use-nullptr.html>`_, `modernize-use-nullptr <modernize-use-nullptr.html>`_, "Yes"
`hicpp-use-override <hicpp-use-override.html>`_, `modernize-use-override <modernize-use-override.html>`_, "Yes"
`hicpp-vararg <hicpp-vararg.html>`_, `cppcoreguidelines-pro-type-vararg <cppcoreguidelines-pro-type-vararg.html>`_,
`llvm-else-after-return <llvm-else-after-return.html>`_, `readability-else-after-return <readability-else-after-return.html>`_, "Yes"
`llvm-qualified-auto <llvm-qualified-auto.html>`_, `readability-qualified-auto <readability-qualified-auto.html>`_, "Yes"
.. title:: clang-tidy - llvm-else-after-return
.. meta::
:http-equiv=refresh: 5;URL=readability-else-after-return.html
llvm-else-after-return
======================
The llvm-else-after-return check is an alias, please see
`readability-else-after-return <readability-else-after-return.html>`_
for more information.
.. title:: clang-tidy - llvm-header-guard
llvm-header-guard
=================
Finds and fixes header guards that do not adhere to LLVM style.
Options
-------
.. option:: HeaderFileExtensions
A comma-separated list of filename extensions of header files (the filename
extensions should not include "." prefix). Default is "h,hh,hpp,hxx".
For header files without an extension, use an empty string (if there are no
other desired extensions) or leave an empty element in the list. e.g.,
"h,hh,hpp,hxx," (note the trailing comma).
.. title:: clang-tidy - llvm-include-order
llvm-include-order
==================
Checks the correct order of ``#includes``.
See https://llvm.org/docs/CodingStandards.html#include-style
.. title:: clang-tidy - llvm-namespace-comment
llvm-namespace-comment
======================
`google-readability-namespace-comments` redirects here as an alias for this
check.
Checks that long namespaces have a closing comment.
https://llvm.org/docs/CodingStandards.html#namespace-indentation
https://google.github.io/styleguide/cppguide.html#Namespaces
.. code-block:: c++
namespace n1 {
void f();
}
// becomes
namespace n1 {
void f();
} // namespace n1
Options
-------
.. option:: ShortNamespaceLines
Requires the closing brace of the namespace definition to be followed by a
closing comment if the body of the namespace has more than
`ShortNamespaceLines` lines of code. The value is an unsigned integer that
defaults to `1U`.
.. option:: SpacesBeforeComments
An unsigned integer specifying the number of spaces before the comment
closing a namespace definition. Default is `1U`.
.. title:: clang-tidy - llvm-prefer-isa-or-dyn-cast-in-conditionals
llvm-prefer-isa-or-dyn-cast-in-conditionals
===========================================
Looks at conditionals and finds and replaces cases of ``cast<>``,
which will assert rather than return a null pointer, and
``dyn_cast<>`` where the return value is not captured. Additionally,
finds and replaces cases that match the pattern ``var &&
isa<X>(var)``, where ``var`` is evaluated twice.
.. code-block:: c++
// Finds these:
if (auto x = cast<X>(y)) {}
// is replaced by:
if (auto x = dyn_cast<X>(y)) {}
if (cast<X>(y)) {}
// is replaced by:
if (isa<X>(y)) {}
if (dyn_cast<X>(y)) {}
// is replaced by:
if (isa<X>(y)) {}
if (var && isa<T>(var)) {}
// is replaced by:
if (isa_and_nonnull<T>(var.foo())) {}
// Other cases are ignored, e.g.:
if (auto f = cast<Z>(y)->foo()) {}
if (cast<Z>(y)->foo()) {}
if (X.cast(y)) {}
.. title:: clang-tidy - llvm-prefer-register-over-unsigned
llvm-prefer-register-over-unsigned
==================================
Finds historical use of ``unsigned`` to hold vregs and physregs and rewrites
them to use ``Register``.
Currently this works by finding all variables of unsigned integer type whose
initializer begins with an implicit cast from ``Register`` to ``unsigned``.
.. code-block:: c++
void example(MachineOperand &MO) {
unsigned Reg = MO.getReg();
...
}
becomes:
.. code-block:: c++
void example(MachineOperand &MO) {
Register Reg = MO.getReg();
...
}
.. title:: clang-tidy - llvm-qualified-auto
.. meta::
:http-equiv=refresh: 5;URL=readability-qualified-auto.html
llvm-qualified-auto
===================
The llvm-qualified-auto check is an alias, please see
`readability-qualified-auto <readability-qualified-auto.html>`_
for more information.
.. title:: clang-tidy - llvm-twine-local
llvm-twine-local
================
Looks for local ``Twine`` variables which are prone to use after frees and
should be generally avoided.
.. code-block:: c++
static Twine Moo = Twine("bark") + "bah";
// becomes
static std::string Moo = (Twine("bark") + "bah").str();
.. title:: clang-tidy - llvmlibc-callee-namespace
llvmlibc-callee-namespace
====================================
Checks all calls resolve to functions within ``__llvm_libc`` namespace.
.. code-block:: c++
namespace __llvm_libc {
// Allow calls with the fully qualified name.
__llvm_libc::strlen("hello");
// Allow calls to compiler provided functions.
(void)__builtin_abs(-1);
// Bare calls are allowed as long as they resolve to the correct namespace.
strlen("world");
// Disallow calling into functions in the global namespace.
::strlen("!");
} // namespace __llvm_libc
.. title:: clang-tidy - llvmlibc-implementation-in-namespace
llvmlibc-implementation-in-namespace
====================================
Checks that all declarations in the llvm-libc implementation are within the
correct namespace.
.. code-block:: c++
// Correct: implementation inside the correct namespace.
namespace __llvm_libc {
void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
// Namespaces within __llvm_libc namespace are allowed.
namespace inner{
int localVar = 0;
}
// Functions with C linkage are allowed.
extern "C" void str_fuzz(){}
}
// Incorrect: implementation not in a namespace.
void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
// Incorrect: outer most namespace is not correct.
namespace something_else {
void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
}
.. title:: clang-tidy - llvmlibc-restrict-system-libc-headers
llvmlibc-restrict-system-libc-headers
=====================================
Finds includes of system libc headers not provided by the compiler within
llvm-libc implementations.
.. code-block:: c++
#include <stdio.h> // Not allowed because it is part of system libc.
#include <stddef.h> // Allowed because it is provided by the compiler.
#include "internal/stdio.h" // Allowed because it is NOT part of system libc.
This check is necessary because accidentally including system libc headers can
lead to subtle and hard to detect bugs. For example consider a system libc
whose ``dirent`` struct has slightly different field ordering than llvm-libc.
While this will compile successfully, this can cause issues during runtime
because they are ABI incompatible.
Options
-------
.. option:: Includes
A string containing a comma separated glob list of allowed include
filenames. Similar to the -checks glob list for running clang-tidy itself,
the two wildcard characters are `*` and `-`, to include and exclude globs,
respectively. The default is `-*`, which disallows all includes.
This can be used to allow known safe includes such as Linux development
headers. See :doc:`portability-restrict-system-includes
<portability-restrict-system-includes>` for more
details.
.. title:: clang-tidy - misc-definitions-in-headers
misc-definitions-in-headers
===========================
Finds non-extern non-inline function and variable definitions in header files,
which can lead to potential ODR violations in case these headers are included
from multiple translation units.
.. code-block:: c++
// Foo.h
int a = 1; // Warning: variable definition.
extern int d; // OK: extern variable.
namespace N {
int e = 2; // Warning: variable definition.
}
// Warning: variable definition.
const char* str = "foo";
// OK: internal linkage variable definitions are ignored for now.
// Although these might also cause ODR violations, we can be less certain and
// should try to keep the false-positive rate down.
static int b = 1;
const int c = 1;
const char* const str2 = "foo";
constexpr int k = 1;
// Warning: function definition.
int g() {
return 1;
}
// OK: inline function definition is allowed to be defined multiple times.
inline int e() {
return 1;
}
class A {
public:
int f1() { return 1; } // OK: implicitly inline member function definition is allowed.
int f2();
static int d;
};
// Warning: not an inline member function definition.
int A::f2() { return 1; }
// OK: class static data member declaration is allowed.
int A::d = 1;
// OK: function template is allowed.
template<typename T>
T f3() {
T a = 1;
return a;
}
// Warning: full specialization of a function template is not allowed.
template <>
int f3() {
int a = 1;
return a;
}
template <typename T>
struct B {
void f1();
};
// OK: member function definition of a class template is allowed.
template <typename T>
void B<T>::f1() {}
class CE {
constexpr static int i = 5; // OK: inline variable definition.
};
inline int i = 5; // OK: inline variable definition.
constexpr int f10() { return 0; } // OK: constexpr function implies inline.
// OK: C++14 variable templates are inline.
template <class T>
constexpr T pi = T(3.1415926L);
Options
-------
.. option:: HeaderFileExtensions
A comma-separated list of filename extensions of header files (the filename
extensions should not include "." prefix). Default is "h,hh,hpp,hxx".
For header files without an extension, use an empty string (if there are no
other desired extensions) or leave an empty element in the list. e.g.,
"h,hh,hpp,hxx," (note the trailing comma).
.. option:: UseHeaderFileExtension
When `true`, the check will use the file extension to distinguish header
files. Default is `true`.
.. title:: clang-tidy - misc-misplaced-const
misc-misplaced-const
====================
This check diagnoses when a ``const`` qualifier is applied to a ``typedef``/
``using`` to a pointer type rather than to the pointee, because such constructs
are often misleading to developers because the ``const`` applies to the pointer
rather than the pointee.
For instance, in the following code, the resulting type is ``int * const``
rather than ``const int *``:
.. code-block:: c++
typedef int *int_ptr;
void f(const int_ptr ptr) {
*ptr = 0; // potentially quite unexpectedly the int can be modified here
ptr = 0; // does not compile
}
The check does not diagnose when the underlying ``typedef``/``using`` type is a
pointer to a ``const`` type or a function pointer type. This is because the
``const`` qualifier is less likely to be mistaken because it would be redundant
(or disallowed) on the underlying pointee type.
.. title:: clang-tidy - misc-new-delete-overloads
misc-new-delete-overloads
=========================
`cert-dcl54-cpp` redirects here as an alias for this check.
The check flags overloaded operator ``new()`` and operator ``delete()``
functions that do not have a corresponding free store function defined within
the same scope.
For instance, the check will flag a class implementation of a non-placement
operator ``new()`` when the class does not also define a non-placement operator
``delete()`` function as well.
The check does not flag implicitly-defined operators, deleted or private
operators, or placement operators.
This check corresponds to CERT C++ Coding Standard rule `DCL54-CPP. Overload allocation and deallocation functions as a pair in the same scope
<https://www.securecoding.cert.org/confluence/display/cplusplus/DCL54-CPP.+Overload+allocation+and+deallocation+functions+as+a+pair+in+the+same+scope>`_.
.. title:: clang-tidy - misc-no-recursion
misc-no-recursion
=================
Finds strongly connected functions (by analyzing the call graph for
SCC's (Strongly Connected Components) that are loops),
diagnoses each function in the cycle,
and displays one example of a possible call graph loop (recursion).
References:
* CERT C++ Coding Standard rule `DCL56-CPP. Avoid cycles during initialization of static objects <https://wiki.sei.cmu.edu/confluence/display/cplusplus/DCL56-CPP.+Avoid+cycles+during+initialization+of+static+objects>`_.
* JPL Institutional Coding Standard for the C Programming Language (JPL DOCID D-60411) rule `2.4 Do not use direct or indirect recursion`.
* OpenCL Specification, Version 1.2 rule `6.9 Restrictions: i. Recursion is not supported. <https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf>`_.
Limitations:
* The check does not handle calls done through function pointers
* The check does not handle C++ destructors
.. title:: clang-tidy - misc-non-copyable-objects
misc-non-copyable-objects
=========================
`cert-fio38-c` redirects here as an alias for this check.
The check flags dereferences and non-pointer declarations of objects that are
not meant to be passed by value, such as C FILE objects or POSIX
``pthread_mutex_t`` objects.
This check corresponds to CERT C++ Coding Standard rule `FIO38-C. Do not copy a FILE object
<https://www.securecoding.cert.org/confluence/display/c/FIO38-C.+Do+not+copy+a+FILE+object>`_.
.. title:: clang-tidy - misc-non-private-member-variables-in-classes
misc-non-private-member-variables-in-classes
============================================
`cppcoreguidelines-non-private-member-variables-in-classes` redirects here
as an alias for this check.
Finds classes that contain non-static data members in addition to user-declared
non-static member functions and diagnose all data members declared with a
non-``public`` access specifier. The data members should be declared as
``private`` and accessed through member functions instead of exposed to derived
classes or class consumers.
Options
-------
.. option:: IgnoreClassesWithAllMemberVariablesBeingPublic
Allows to completely ignore classes if **all** the member variables in that
class a declared with a ``public`` access specifier.
.. option:: IgnorePublicMemberVariables
Allows to ignore (not diagnose) **all** the member variables declared with
a ``public`` access specifier.
.. title:: clang-tidy - misc-redundant-expression
misc-redundant-expression
=========================
Detect redundant expressions which are typically errors due to copy-paste.
Depending on the operator expressions may be
- redundant,
- always ``true``,
- always ``false``,
- always a constant (zero or one).
Examples:
.. code-block:: c++
((x+1) | (x+1)) // (x+1) is redundant
(p->x == p->x) // always true
(p->x < p->x) // always false
(speed - speed + 1 == 12) // speed - speed is always zero
.. title:: clang-tidy - misc-static-assert
misc-static-assert
==================
`cert-dcl03-c` redirects here as an alias for this check.
Replaces ``assert()`` with ``static_assert()`` if the condition is evaluatable
at compile time.
The condition of ``static_assert()`` is evaluated at compile time which is
safer and more efficient.
.. title:: clang-tidy - misc-throw-by-value-catch-by-reference
misc-throw-by-value-catch-by-reference
======================================
`cert-err09-cpp` redirects here as an alias for this check.
`cert-err61-cpp` redirects here as an alias for this check.
Finds violations of the rule "Throw by value, catch by reference" presented for
example in "C++ Coding Standards" by H. Sutter and A. Alexandrescu, as well as
the CERT C++ Coding Standard rule `ERR61-CPP. Catch exceptions by lvalue reference
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/ERR61-CPP.+Catch+exceptions+by+lvalue+reference>`_.
Exceptions:
* Throwing string literals will not be flagged despite being a pointer. They
are not susceptible to slicing and the usage of string literals is idomatic.
* Catching character pointers (``char``, ``wchar_t``, unicode character types)
will not be flagged to allow catching sting literals.
* Moved named values will not be flagged as not throwing an anonymous
temporary. In this case we can be sure that the user knows that the object
can't be accessed outside catch blocks handling the error.
* Throwing function parameters will not be flagged as not throwing an
anonymous temporary. This allows helper functions for throwing.
* Re-throwing caught exception variables will not be flragged as not throwing
an anonymous temporary. Although this can usually be done by just writing
``throw;`` it happens often enough in real code.
Options
-------
.. option:: CheckThrowTemporaries
Triggers detection of violations of the CERT recommendation ERR09-CPP. Throw
anonymous temporaries.
Default is `true`.
.. option:: WarnOnLargeObject
Also warns for any large, trivial object caught by value. Catching a large
object by value is not dangerous but affects the performance negatively. The
maximum size of an object allowed to be caught without warning can be set
using the `MaxSize` option.
Default is `false`.
.. option:: MaxSize
Determines the maximum size of an object allowed to be caught without
warning. Only applicable if :option:`WarnOnLargeObject` is set to `true`. If
the option is set by the user to `std::numeric_limits<uint64_t>::max()` then
it reverts to the default value.
Default is the size of `size_t`.
.. title:: clang-tidy - misc-unconventional-assign-operator
misc-unconventional-assign-operator
===================================
Finds declarations of assign operators with the wrong return and/or argument
types and definitions with good return type but wrong ``return`` statements.
* The return type must be ``Class&``.
* Works with move-assign and assign by value.
* Private and deleted operators are ignored.
* The operator must always return ``*this``.
.. title:: clang-tidy - misc-uniqueptr-reset-release
misc-uniqueptr-reset-release
============================
Find and replace ``unique_ptr::reset(release())`` with ``std::move()``.
Example:
.. code-block:: c++
std::unique_ptr<Foo> x, y;
x.reset(y.release()); -> x = std::move(y);
If ``y`` is already rvalue, ``std::move()`` is not added. ``x`` and ``y`` can
also be ``std::unique_ptr<Foo>*``.
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. title:: clang-tidy - misc-unused-alias-decls
misc-unused-alias-decls
=======================
Finds unused namespace alias declarations.
.. code-block:: c++
namespace my_namespace {
class C {};
}
namespace unused_alias = ::my_namespace;
.. title:: clang-tidy - misc-unused-parameters
misc-unused-parameters
======================
Finds unused function parameters. Unused parameters may signify a bug in the
code (e.g. when a different parameter is used instead). The suggested fixes
either comment parameter name out or remove the parameter completely, if all
callers of the function are in the same translation unit and can be updated.
The check is similar to the ``-Wunused-parameter`` compiler diagnostic and can be
used to prepare a codebase to enabling of that diagnostic. By default the check
is more permissive (see :option:`StrictMode`).
.. code-block:: c++
void a(int i) { /*some code that doesn't use `i`*/ }
// becomes
void a(int /*i*/) { /*some code that doesn't use `i`*/ }
.. code-block:: c++
static void staticFunctionA(int i);
static void staticFunctionA(int i) { /*some code that doesn't use `i`*/ }
// becomes
static void staticFunctionA()
static void staticFunctionA() { /*some code that doesn't use `i`*/ }
Options
-------
.. option:: StrictMode
When `false` (default value), the check will ignore trivially unused parameters,
i.e. when the corresponding function has an empty body (and in case of
constructors - no constructor initializers). When the function body is empty,
an unused parameter is unlikely to be unnoticed by a human reader, and
there's basically no place for a bug to hide.
.. title:: clang-tidy - misc-unused-using-decls
misc-unused-using-decls
=======================
Finds unused ``using`` declarations.
Example:
.. code-block:: c++
namespace n { class C; }
using n::C; // Never actually used.
.. title:: clang-tidy - modernize-avoid-bind
modernize-avoid-bind
====================
The check finds uses of ``std::bind`` and ``boost::bind`` and replaces them
with lambdas. Lambdas will use value-capture unless reference capture is
explicitly requested with ``std::ref`` or ``boost::ref``.
It supports arbitrary callables including member functions, function objects,
and free functions, and all variations thereof. Anything that you can pass
to the first argument of ``bind`` should be diagnosable. Currently, the only
known case where a fix-it is unsupported is when the same placeholder is
specified multiple times in the parameter list.
Given:
.. code-block:: c++
int add(int x, int y) { return x + y; }
Then:
.. code-block:: c++
void f() {
int x = 2;
auto clj = std::bind(add, x, _1);
}
is replaced by:
.. code-block:: c++
void f() {
int x = 2;
auto clj = [=](auto && arg1) { return add(x, arg1); };
}
``std::bind`` can be hard to read and can result in larger object files and
binaries due to type information that will not be produced by equivalent
lambdas.
Options
-------
.. option:: PermissiveParameterList
If the option is set to `true`, the check will append ``auto&&...`` to the end
of every placeholder parameter list. Without this, it is possible for a fix-it
to perform an incorrect transformation in the case where the result of the ``bind``
is used in the context of a type erased functor such as ``std::function`` which
allows mismatched arguments. For example:
.. code-block:: c++
int add(int x, int y) { return x + y; }
int foo() {
std::function<int(int,int)> ignore_args = std::bind(add, 2, 2);
return ignore_args(3, 3);
}
is valid code, and returns `4`. The actual values passed to ``ignore_args`` are
simply ignored. Without ``PermissiveParameterList``, this would be transformed into
.. code-block:: c++
int add(int x, int y) { return x + y; }
int foo() {
std::function<int(int,int)> ignore_args = [] { return add(2, 2); }
return ignore_args(3, 3);
}
which will *not* compile, since the lambda does not contain an ``operator()`` that
that accepts 2 arguments. With permissive parameter list, it instead generates
.. code-block:: c++
int add(int x, int y) { return x + y; }
int foo() {
std::function<int(int,int)> ignore_args = [](auto&&...) { return add(2, 2); }
return ignore_args(3, 3);
}
which is correct.
This check requires using C++14 or higher to run.
.. title:: clang-tidy - modernize-avoid-c-arrays
modernize-avoid-c-arrays
========================
`cppcoreguidelines-avoid-c-arrays` redirects here as an alias for this check.
`hicpp-avoid-c-arrays` redirects here as an alias for this check.
Finds C-style array types and recommend to use ``std::array<>`` /
``std::vector<>``. All types of C arrays are diagnosed.
However, fix-it are potentially dangerous in header files and are therefore not
emitted right now.
.. code:: c++
int a[] = {1, 2}; // warning: do not declare C-style arrays, use std::array<> instead
int b[1]; // warning: do not declare C-style arrays, use std::array<> instead
void foo() {
int c[b[0]]; // warning: do not declare C VLA arrays, use std::vector<> instead
}
template <typename T, int Size>
class array {
T d[Size]; // warning: do not declare C-style arrays, use std::array<> instead
int e[1]; // warning: do not declare C-style arrays, use std::array<> instead
};
array<int[4], 2> d; // warning: do not declare C-style arrays, use std::array<> instead
using k = int[4]; // warning: do not declare C-style arrays, use std::array<> instead
However, the ``extern "C"`` code is ignored, since it is common to share
such headers between C code, and C++ code.
.. code:: c++
// Some header
extern "C" {
int f[] = {1, 2}; // not diagnosed
int j[1]; // not diagnosed
inline void bar() {
{
int j[j[0]]; // not diagnosed
}
}
}
Similarly, the ``main()`` function is ignored. Its second and third parameters
can be either ``char* argv[]`` or ``char** argv``, but can not be
``std::array<>``.
.. title:: clang-tidy - modernize-concat-nested-namespaces
modernize-concat-nested-namespaces
==================================
Checks for use of nested namespaces such as ``namespace a { namespace b { ... } }``
and suggests changing to the more concise syntax introduced in C++17: ``namespace a::b { ... }``.
Inline namespaces are not modified.
For example:
.. code-block:: c++
namespace n1 {
namespace n2 {
void t();
}
}
namespace n3 {
namespace n4 {
namespace n5 {
void t();
}
}
namespace n6 {
namespace n7 {
void t();
}
}
}
Will be modified to:
.. code-block:: c++
namespace n1::n2 {
void t();
}
namespace n3 {
namespace n4::n5 {
void t();
}
namespace n6::n7 {
void t();
}
}
.. title:: clang-tidy - modernize-deprecated-headers
modernize-deprecated-headers
============================
Some headers from C library were deprecated in C++ and are no longer welcome in
C++ codebases. Some have no effect in C++. For more details refer to the C++ 14
Standard [depr.c.headers] section.
This check replaces C standard library headers with their C++ alternatives and
removes redundant ones.
Important note: the Standard doesn't guarantee that the C++ headers declare all
the same functions in the global namespace. The check in its current form can
break the code that uses library symbols from the global namespace.
* `<assert.h>`
* `<complex.h>`
* `<ctype.h>`
* `<errno.h>`
* `<fenv.h>` // deprecated since C++11
* `<float.h>`
* `<inttypes.h>`
* `<limits.h>`
* `<locale.h>`
* `<math.h>`
* `<setjmp.h>`
* `<signal.h>`
* `<stdarg.h>`
* `<stddef.h>`
* `<stdint.h>`
* `<stdio.h>`
* `<stdlib.h>`
* `<string.h>`
* `<tgmath.h>` // deprecated since C++11
* `<time.h>`
* `<uchar.h>` // deprecated since C++11
* `<wchar.h>`
* `<wctype.h>`
If the specified standard is older than C++11 the check will only replace
headers deprecated before C++11, otherwise -- every header that appeared in
the previous list.
These headers don't have effect in C++:
* `<iso646.h>`
* `<stdalign.h>`
* `<stdbool.h>`
.. title:: clang-tidy - modernize-deprecated-ios-base-aliases
modernize-deprecated-ios-base-aliases
=====================================
Detects usage of the deprecated member types of ``std::ios_base`` and replaces
those that have a non-deprecated equivalent.
=================================== ===========================
Deprecated member type Replacement
=================================== ===========================
``std::ios_base::io_state`` ``std::ios_base::iostate``
``std::ios_base::open_mode`` ``std::ios_base::openmode``
``std::ios_base::seek_dir`` ``std::ios_base::seekdir``
``std::ios_base::streamoff``
``std::ios_base::streampos``
=================================== ===========================
.. title:: clang-tidy - modernize-loop-convert
modernize-loop-convert
======================
This check converts ``for(...; ...; ...)`` loops to use the new range-based
loops in C++11.
Three kinds of loops can be converted:
- Loops over statically allocated arrays.
- Loops over containers, using iterators.
- Loops over array-like containers, using ``operator[]`` and ``at()``.
MinConfidence option
--------------------
risky
^^^^^
In loops where the container expression is more complex than just a
reference to a declared expression (a variable, function, enum, etc.),
and some part of it appears elsewhere in the loop, we lower our confidence
in the transformation due to the increased risk of changing semantics.
Transformations for these loops are marked as `risky`, and thus will only
be converted if the minimum required confidence level is set to `risky`.
.. code-block:: c++
int arr[10][20];
int l = 5;
for (int j = 0; j < 20; ++j)
int k = arr[l][j] + l; // using l outside arr[l] is considered risky
for (int i = 0; i < obj.getVector().size(); ++i)
obj.foo(10); // using 'obj' is considered risky
See
:ref:`Range-based loops evaluate end() only once<IncorrectRiskyTransformation>`
for an example of an incorrect transformation when the minimum required confidence
level is set to `risky`.
reasonable (Default)
^^^^^^^^^^^^^^^^^^^^
If a loop calls ``.end()`` or ``.size()`` after each iteration, the
transformation for that loop is marked as `reasonable`, and thus will
be converted if the required confidence level is set to `reasonable`
(default) or lower.
.. code-block:: c++
// using size() is considered reasonable
for (int i = 0; i < container.size(); ++i)
cout << container[i];
safe
^^^^
Any other loops that do not match the above criteria to be marked as
`risky` or `reasonable` are marked `safe`, and thus will be converted
if the required confidence level is set to `safe` or lower.
.. code-block:: c++
int arr[] = {1,2,3};
for (int i = 0; i < 3; ++i)
cout << arr[i];
Example
-------
Original:
.. code-block:: c++
const int N = 5;
int arr[] = {1,2,3,4,5};
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
// safe conversion
for (int i = 0; i < N; ++i)
cout << arr[i];
// reasonable conversion
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
cout << *it;
// reasonable conversion
for (int i = 0; i < v.size(); ++i)
cout << v[i];
After applying the check with minimum confidence level set to `reasonable` (default):
.. code-block:: c++
const int N = 5;
int arr[] = {1,2,3,4,5};
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
// safe conversion
for (auto & elem : arr)
cout << elem;
// reasonable conversion
for (auto & elem : v)
cout << elem;
// reasonable conversion
for (auto & elem : v)
cout << elem;
Reverse Iterator Support
------------------------
The converter is also capable of transforming iterator loops which use
``rbegin`` and ``rend`` for looping backwards over a container. Out of the box
this will automatically happen in C++20 mode using the ``ranges`` library,
however the check can be configured to work without C++20 by specifying a
function to reverse a range and optionally the header file where that function
lives.
.. option:: UseCxx20ReverseRanges
When set to true convert loops when in C++20 or later mode using
``std::ranges::reverse_view``.
Default value is ``true``.
.. option:: MakeReverseRangeFunction
Specify the function used to reverse an iterator pair, the function should
accept a class with ``rbegin`` and ``rend`` methods and return a
class with ``begin`` and ``end`` methods methods that call the ``rbegin`` and
``rend`` methods respectively. Common examples are ``ranges::reverse_view``
and ``llvm::reverse``.
Default value is an empty string.
.. option:: MakeReverseRangeHeader
Specifies the header file where :option:`MakeReverseRangeFunction` is
declared. For the previous examples this option would be set to
``range/v3/view/reverse.hpp`` and ``llvm/ADT/STLExtras.h`` respectively.
If this is an empty string and :option:`MakeReverseRangeFunction` is set,
the check will proceed on the assumption that the function is already
available in the translation unit.
This can be wrapped in angle brackets to signify to add the include as a
system include.
Default value is an empty string.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
Limitations
-----------
There are certain situations where the tool may erroneously perform
transformations that remove information and change semantics. Users of the tool
should be aware of the behaviour and limitations of the check outlined by
the cases below.
Comments inside loop headers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Comments inside the original loop header are ignored and deleted when
transformed.
.. code-block:: c++
for (int i = 0; i < N; /* This will be deleted */ ++i) { }
Range-based loops evaluate end() only once
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The C++11 range-based for loop calls ``.end()`` only once during the
initialization of the loop. If in the original loop ``.end()`` is called after
each iteration the semantics of the transformed loop may differ.
.. code-block:: c++
// The following is semantically equivalent to the C++11 range-based for loop,
// therefore the semantics of the header will not change.
for (iterator it = container.begin(), e = container.end(); it != e; ++it) { }
// Instead of calling .end() after each iteration, this loop will be
// transformed to call .end() only once during the initialization of the loop,
// which may affect semantics.
for (iterator it = container.begin(); it != container.end(); ++it) { }
.. _IncorrectRiskyTransformation:
As explained above, calling member functions of the container in the body
of the loop is considered `risky`. If the called member function modifies the
container the semantics of the converted loop will differ due to ``.end()``
being called only once.
.. code-block:: c++
bool flag = false;
for (vector<T>::iterator it = vec.begin(); it != vec.end(); ++it) {
// Add a copy of the first element to the end of the vector.
if (!flag) {
// This line makes this transformation 'risky'.
vec.push_back(*it);
flag = true;
}
cout << *it;
}
The original code above prints out the contents of the container including the
newly added element while the converted loop, shown below, will only print the
original contents and not the newly added element.
.. code-block:: c++
bool flag = false;
for (auto & elem : vec) {
// Add a copy of the first element to the end of the vector.
if (!flag) {
// This line makes this transformation 'risky'
vec.push_back(elem);
flag = true;
}
cout << elem;
}
Semantics will also be affected if ``.end()`` has side effects. For example, in
the case where calls to ``.end()`` are logged the semantics will change in the
transformed loop if ``.end()`` was originally called after each iteration.
.. code-block:: c++
iterator end() {
num_of_end_calls++;
return container.end();
}
Overloaded operator->() with side effects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Similarly, if ``operator->()`` was overloaded to have side effects, such as
logging, the semantics will change. If the iterator's ``operator->()`` was used
in the original loop it will be replaced with ``<container element>.<member>``
instead due to the implicit dereference as part of the range-based for loop.
Therefore any side effect of the overloaded ``operator->()`` will no longer be
performed.
.. code-block:: c++
for (iterator it = c.begin(); it != c.end(); ++it) {
it->func(); // Using operator->()
}
// Will be transformed to:
for (auto & elem : c) {
elem.func(); // No longer using operator->()
}
Pointers and references to containers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
While most of the check's risk analysis is dedicated to determining whether
the iterator or container was modified within the loop, it is possible to
circumvent the analysis by accessing and modifying the container through a
pointer or reference.
If the container were directly used instead of using the pointer or reference
the following transformation would have only been applied at the `risky`
level since calling a member function of the container is considered `risky`.
The check cannot identify expressions associated with the container that are
different than the one used in the loop header, therefore the transformation
below ends up being performed at the `safe` level.
.. code-block:: c++
vector<int> vec;
vector<int> *ptr = &vec;
vector<int> &ref = vec;
for (vector<int>::iterator it = vec.begin(), e = vec.end(); it != e; ++it) {
if (!flag) {
// Accessing and modifying the container is considered risky, but the risk
// level is not raised here.
ptr->push_back(*it);
ref.push_back(*it);
flag = true;
}
}
OpenMP
^^^^^^
As range-based for loops are only available since OpenMP 5, this check should
not been used on code with a compatibility requirements of OpenMP prior to
version 5. It is **intentional** that this check does not make any attempts to
exclude incorrect diagnostics on OpenMP for loops prior to OpenMP 5.
To prevent this check to be applied (and to break) OpenMP for loops but still be
applied to non-OpenMP for loops the usage of ``NOLINT`` (see
:ref:`clang-tidy-nolint`) on the specific for loops is recommended.
.. title:: clang-tidy - modernize-make-shared
modernize-make-shared
=====================
This check finds the creation of ``std::shared_ptr`` objects by explicitly
calling the constructor and a ``new`` expression, and replaces it with a call
to ``std::make_shared``.
.. code-block:: c++
auto my_ptr = std::shared_ptr<MyPair>(new MyPair(1, 2));
// becomes
auto my_ptr = std::make_shared<MyPair>(1, 2);
This check also finds calls to ``std::shared_ptr::reset()`` with a ``new``
expression, and replaces it with a call to ``std::make_shared``.
.. code-block:: c++
my_ptr.reset(new MyPair(1, 2));
// becomes
my_ptr = std::make_shared<MyPair>(1, 2);
Options
-------
.. option:: MakeSmartPtrFunction
A string specifying the name of make-shared-ptr function. Default is
`std::make_shared`.
.. option:: MakeSmartPtrFunctionHeader
A string specifying the corresponding header of make-shared-ptr function.
Default is `memory`.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. option:: IgnoreDefaultInitialization
If set to non-zero, the check does not suggest edits that will transform
default initialization into value initialization, as this can cause
performance regressions. Default is `1`.
.. title:: clang-tidy - modernize-make-unique
modernize-make-unique
=====================
This check finds the creation of ``std::unique_ptr`` objects by explicitly
calling the constructor and a ``new`` expression, and replaces it with a call
to ``std::make_unique``, introduced in C++14.
.. code-block:: c++
auto my_ptr = std::unique_ptr<MyPair>(new MyPair(1, 2));
// becomes
auto my_ptr = std::make_unique<MyPair>(1, 2);
This check also finds calls to ``std::unique_ptr::reset()`` with a ``new``
expression, and replaces it with a call to ``std::make_unique``.
.. code-block:: c++
my_ptr.reset(new MyPair(1, 2));
// becomes
my_ptr = std::make_unique<MyPair>(1, 2);
Options
-------
.. option:: MakeSmartPtrFunction
A string specifying the name of make-unique-ptr function. Default is
`std::make_unique`.
.. option:: MakeSmartPtrFunctionHeader
A string specifying the corresponding header of make-unique-ptr function.
Default is `<memory>`.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. option:: IgnoreDefaultInitialization
If set to non-zero, the check does not suggest edits that will transform
default initialization into value initialization, as this can cause
performance regressions. Default is `1`.
.. title:: clang-tidy - modernize-pass-by-value
modernize-pass-by-value
=======================
With move semantics added to the language and the standard library updated with
move constructors added for many types it is now interesting to take an
argument directly by value, instead of by const-reference, and then copy. This
check allows the compiler to take care of choosing the best way to construct
the copy.
The transformation is usually beneficial when the calling code passes an
*rvalue* and assumes the move construction is a cheap operation. This short
example illustrates how the construction of the value happens:
.. code-block:: c++
void foo(std::string s);
std::string get_str();
void f(const std::string &str) {
foo(str); // lvalue -> copy construction
foo(get_str()); // prvalue -> move construction
}
.. note::
Currently, only constructors are transformed to make use of pass-by-value.
Contributions that handle other situations are welcome!
Pass-by-value in constructors
-----------------------------
Replaces the uses of const-references constructor parameters that are copied
into class fields. The parameter is then moved with `std::move()`.
Since ``std::move()`` is a library function declared in `<utility>` it may be
necessary to add this include. The check will add the include directive when
necessary.
.. code-block:: c++
#include <string>
class Foo {
public:
- Foo(const std::string &Copied, const std::string &ReadOnly)
- : Copied(Copied), ReadOnly(ReadOnly)
+ Foo(std::string Copied, const std::string &ReadOnly)
+ : Copied(std::move(Copied)), ReadOnly(ReadOnly)
{}
private:
std::string Copied;
const std::string &ReadOnly;
};
std::string get_cwd();
void f(const std::string &Path) {
// The parameter corresponding to 'get_cwd()' is move-constructed. By
// using pass-by-value in the Foo constructor we managed to avoid a
// copy-construction.
Foo foo(get_cwd(), Path);
}
If the parameter is used more than once no transformation is performed since
moved objects have an undefined state. It means the following code will be left
untouched:
.. code-block:: c++
#include <string>
void pass(const std::string &S);
struct Foo {
Foo(const std::string &S) : Str(S) {
pass(S);
}
std::string Str;
};
Known limitations
^^^^^^^^^^^^^^^^^
A situation where the generated code can be wrong is when the object referenced
is modified before the assignment in the init-list through a "hidden" reference.
Example:
.. code-block:: c++
std::string s("foo");
struct Base {
Base() {
s = "bar";
}
};
struct Derived : Base {
- Derived(const std::string &S) : Field(S)
+ Derived(std::string S) : Field(std::move(S))
{ }
std::string Field;
};
void f() {
- Derived d(s); // d.Field holds "bar"
+ Derived d(s); // d.Field holds "foo"
}
Note about delayed template parsing
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When delayed template parsing is enabled, constructors part of templated
contexts; templated constructors, constructors in class templates, constructors
of inner classes of template classes, etc., are not transformed. Delayed
template parsing is enabled by default on Windows as a Microsoft extension:
`Clang Compiler User’s Manual - Microsoft extensions`_.
Delayed template parsing can be enabled using the `-fdelayed-template-parsing`
flag and disabled using `-fno-delayed-template-parsing`.
Example:
.. code-block:: c++
template <typename T> class C {
std::string S;
public:
= // using -fdelayed-template-parsing (default on Windows)
= C(const std::string &S) : S(S) {}
+ // using -fno-delayed-template-parsing (default on non-Windows systems)
+ C(std::string S) : S(std::move(S)) {}
};
.. _Clang Compiler User’s Manual - Microsoft extensions: https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
.. seealso::
For more information about the pass-by-value idiom, read: `Want Speed? Pass by Value`_.
.. _Want Speed? Pass by Value: https://web.archive.org/web/20140205194657/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: ValuesOnly
When `true`, the check only warns about copied parameters that are already
passed by value. Default is `false`.
.. title:: clang-tidy - modernize-raw-string-literal
modernize-raw-string-literal
============================
This check selectively replaces string literals containing escaped characters
with raw string literals.
Example:
.. code-blocK:: c++
const char *const Quotes{"embedded \"quotes\""};
const char *const Paragraph{"Line one.\nLine two.\nLine three.\n"};
const char *const SingleLine{"Single line.\n"};
const char *const TrailingSpace{"Look here -> \n"};
const char *const Tab{"One\tTwo\n"};
const char *const Bell{"Hello!\a And welcome!"};
const char *const Path{"C:\\Program Files\\Vendor\\Application.exe"};
const char *const RegEx{"\\w\\([a-z]\\)"};
becomes
.. code-block:: c++
const char *const Quotes{R"(embedded "quotes")"};
const char *const Paragraph{"Line one.\nLine two.\nLine three.\n"};
const char *const SingleLine{"Single line.\n"};
const char *const TrailingSpace{"Look here -> \n"};
const char *const Tab{"One\tTwo\n"};
const char *const Bell{"Hello!\a And welcome!"};
const char *const Path{R"(C:\Program Files\Vendor\Application.exe)"};
const char *const RegEx{R"(\w\([a-z]\))"};
The presence of any of the following escapes can cause the string to be
converted to a raw string literal: ``\\``, ``\'``, ``\"``, ``\?``,
and octal or hexadecimal escapes for printable ASCII characters.
A string literal containing only escaped newlines is a common way of
writing lines of text output. Introducing physical newlines with raw
string literals in this case is likely to impede readability. These
string literals are left unchanged.
An escaped horizontal tab, form feed, or vertical tab prevents the string
literal from being converted. The presence of a horizontal tab, form feed or
vertical tab in source code is not visually obvious.
.. title:: clang-tidy - modernize-redundant-void-arg
modernize-redundant-void-arg
============================
Find and remove redundant ``void`` argument lists.
Examples:
=================================== ===========================
Initial code Code with applied fixes
=================================== ===========================
``int f(void);`` ``int f();``
``int (*f(void))(void);`` ``int (*f())();``
``typedef int (*f_t(void))(void);`` ``typedef int (*f_t())();``
``void (C::*p)(void);`` ``void (C::*p)();``
``C::C(void) {}`` ``C::C() {}``
``C::~C(void) {}`` ``C::~C() {}``
=================================== ===========================
.. title:: clang-tidy - modernize-replace-auto-ptr
modernize-replace-auto-ptr
==========================
This check replaces the uses of the deprecated class ``std::auto_ptr`` by
``std::unique_ptr`` (introduced in C++11). The transfer of ownership, done
by the copy-constructor and the assignment operator, is changed to match
``std::unique_ptr`` usage by using explicit calls to ``std::move()``.
Migration example:
.. code-block:: c++
-void take_ownership_fn(std::auto_ptr<int> int_ptr);
+void take_ownership_fn(std::unique_ptr<int> int_ptr);
void f(int x) {
- std::auto_ptr<int> a(new int(x));
- std::auto_ptr<int> b;
+ std::unique_ptr<int> a(new int(x));
+ std::unique_ptr<int> b;
- b = a;
- take_ownership_fn(b);
+ b = std::move(a);
+ take_ownership_fn(std::move(b));
}
Since ``std::move()`` is a library function declared in ``<utility>`` it may be
necessary to add this include. The check will add the include directive when
necessary.
Known Limitations
-----------------
* If headers modification is not activated or if a header is not allowed to be
changed this check will produce broken code (compilation error), where the
headers' code will stay unchanged while the code using them will be changed.
* Client code that declares a reference to an ``std::auto_ptr`` coming from
code that can't be migrated (such as a header coming from a 3\ :sup:`rd`
party library) will produce a compilation error after migration. This is
because the type of the reference will be changed to ``std::unique_ptr`` but
the type returned by the library won't change, binding a reference to
``std::unique_ptr`` from an ``std::auto_ptr``. This pattern doesn't make much
sense and usually ``std::auto_ptr`` are stored by value (otherwise what is
the point in using them instead of a reference or a pointer?).
.. code-block:: c++
// <3rd-party header...>
std::auto_ptr<int> get_value();
const std::auto_ptr<int> & get_ref();
// <calling code (with migration)...>
-std::auto_ptr<int> a(get_value());
+std::unique_ptr<int> a(get_value()); // ok, unique_ptr constructed from auto_ptr
-const std::auto_ptr<int> & p = get_ptr();
+const std::unique_ptr<int> & p = get_ptr(); // won't compile
* Non-instantiated templates aren't modified.
.. code-block:: c++
template <typename X>
void f() {
std::auto_ptr<X> p;
}
// only 'f<int>()' (or similar) will trigger the replacement.
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. title:: clang-tidy - modernize-replace-disallow-copy-and-assign-macro
modernize-replace-disallow-copy-and-assign-macro
================================================
Finds macro expansions of ``DISALLOW_COPY_AND_ASSIGN(Type)`` and replaces them
with a deleted copy constructor and a deleted assignment operator.
Before the ``delete`` keyword was introduced in C++11 it was common practice to
declare a copy constructor and an assignment operator as a private members. This
effectively makes them unusable to the public API of a class.
With the advent of the ``delete`` keyword in C++11 we can abandon the
``private`` access of the copy constructor and the assignment operator and
delete the methods entirely.
When running this check on a code like this:
.. code-block:: c++
class Foo {
private:
DISALLOW_COPY_AND_ASSIGN(Foo);
};
It will be transformed to this:
.. code-block:: c++
class Foo {
private:
Foo(const Foo &) = delete;
const Foo &operator=(const Foo &) = delete;
};
Known Limitations
-----------------
* Notice that the migration example above leaves the ``private`` access
specification untouched. You might want to run the check :doc:`modernize-use-equals-delete
<modernize-use-equals-delete>` to get warnings for deleted functions in
private sections.
Options
-------
.. option:: MacroName
A string specifying the macro name whose expansion will be replaced.
Default is `DISALLOW_COPY_AND_ASSIGN`.
See: https://en.cppreference.com/w/cpp/language/function#Deleted_functions
.. title:: clang-tidy - modernize-replace-random-shuffle
modernize-replace-random-shuffle
================================
This check will find occurrences of ``std::random_shuffle`` and replace it with ``std::shuffle``. In C++17 ``std::random_shuffle`` will no longer be available and thus we need to replace it.
Below are two examples of what kind of occurrences will be found and two examples of what it will be replaced with.
.. code-block:: c++
std::vector<int> v;
// First example
std::random_shuffle(vec.begin(), vec.end());
// Second example
std::random_shuffle(vec.begin(), vec.end(), randomFunc);
Both of these examples will be replaced with:
.. code-block:: c++
std::shuffle(vec.begin(), vec.end(), std::mt19937(std::random_device()()));
The second example will also receive a warning that ``randomFunc`` is no longer supported in the same way as before so if the user wants the same functionality, the user will need to change the implementation of the ``randomFunc``.
One thing to be aware of here is that ``std::random_device`` is quite expensive to initialize. So if you are using the code in a performance critical place, you probably want to initialize it elsewhere.
Another thing is that the seeding quality of the suggested fix is quite poor: ``std::mt19937`` has an internal state of 624 32-bit integers, but is only seeded with a single integer. So if you require
higher quality randomness, you should consider seeding better, for example:
.. code-block:: c++
std::shuffle(v.begin(), v.end(), []() {
std::mt19937::result_type seeds[std::mt19937::state_size];
std::random_device device;
std::uniform_int_distribution<typename std::mt19937::result_type> dist;
std::generate(std::begin(seeds), std::end(seeds), [&] { return dist(device); });
std::seed_seq seq(std::begin(seeds), std::end(seeds));
return std::mt19937(seq);
}());
.. title:: clang-tidy - modernize-return-braced-init-list
modernize-return-braced-init-list
=================================
Replaces explicit calls to the constructor in a return with a braced
initializer list. This way the return type is not needlessly duplicated in the
function definition and the return statement.
.. code:: c++
Foo bar() {
Baz baz;
return Foo(baz);
}
// transforms to:
Foo bar() {
Baz baz;
return {baz};
}
.. title:: clang-tidy - modernize-shrink-to-fit
modernize-shrink-to-fit
=======================
Replace copy and swap tricks on shrinkable containers with the
``shrink_to_fit()`` method call.
The ``shrink_to_fit()`` method is more readable and more effective than
the copy and swap trick to reduce the capacity of a shrinkable container.
Note that, the ``shrink_to_fit()`` method is only available in C++11 and up.
.. title:: clang-tidy - modernize-unary-static-assert
modernize-unary-static-assert
=============================
The check diagnoses any ``static_assert`` declaration with an empty string literal
and provides a fix-it to replace the declaration with a single-argument ``static_assert`` declaration.
The check is only applicable for C++17 and later code.
The following code:
.. code-block:: c++
void f_textless(int a) {
static_assert(sizeof(a) <= 10, "");
}
is replaced by:
.. code-block:: c++
void f_textless(int a) {
static_assert(sizeof(a) <= 10);
}
.. title:: clang-tidy - modernize-use-auto
modernize-use-auto
==================
This check is responsible for using the ``auto`` type specifier for variable
declarations to *improve code readability and maintainability*. For example:
.. code-block:: c++
std::vector<int>::iterator I = my_container.begin();
// transforms to:
auto I = my_container.begin();
The ``auto`` type specifier will only be introduced in situations where the
variable type matches the type of the initializer expression. In other words
``auto`` should deduce the same type that was originally spelled in the source.
However, not every situation should be transformed:
.. code-block:: c++
int val = 42;
InfoStruct &I = SomeObject.getInfo();
// Should not become:
auto val = 42;
auto &I = SomeObject.getInfo();
In this example using ``auto`` for builtins doesn't improve readability. In
other situations it makes the code less self-documenting impairing readability
and maintainability. As a result, ``auto`` is used only introduced in specific
situations described below.
Iterators
---------
Iterator type specifiers tend to be long and used frequently, especially in
loop constructs. Since the functions generating iterators have a common format,
the type specifier can be replaced without obscuring the meaning of code while
improving readability and maintainability.
.. code-block:: c++
for (std::vector<int>::iterator I = my_container.begin(),
E = my_container.end();
I != E; ++I) {
}
// becomes
for (auto I = my_container.begin(), E = my_container.end(); I != E; ++I) {
}
The check will only replace iterator type-specifiers when all of the following
conditions are satisfied:
* The iterator is for one of the standard container in ``std`` namespace:
* ``array``
* ``deque``
* ``forward_list``
* ``list``
* ``vector``
* ``map``
* ``multimap``
* ``set``
* ``multiset``
* ``unordered_map``
* ``unordered_multimap``
* ``unordered_set``
* ``unordered_multiset``
* ``queue``
* ``priority_queue``
* ``stack``
* The iterator is one of the possible iterator types for standard containers:
* ``iterator``
* ``reverse_iterator``
* ``const_iterator``
* ``const_reverse_iterator``
* In addition to using iterator types directly, typedefs or other ways of
referring to those types are also allowed. However, implementation-specific
types for which a type like ``std::vector<int>::iterator`` is itself a
typedef will not be transformed. Consider the following examples:
.. code-block:: c++
// The following direct uses of iterator types will be transformed.
std::vector<int>::iterator I = MyVec.begin();
{
using namespace std;
list<int>::iterator I = MyList.begin();
}
// The type specifier for J would transform to auto since it's a typedef
// to a standard iterator type.
typedef std::map<int, std::string>::const_iterator map_iterator;
map_iterator J = MyMap.begin();
// The following implementation-specific iterator type for which
// std::vector<int>::iterator could be a typedef would not be transformed.
__gnu_cxx::__normal_iterator<int*, std::vector> K = MyVec.begin();
* The initializer for the variable being declared is not a braced initializer
list. Otherwise, use of ``auto`` would cause the type of the variable to be
deduced as ``std::initializer_list``.
New expressions
---------------
Frequently, when a pointer is declared and initialized with ``new``, the
pointee type is written twice: in the declaration type and in the
``new`` expression. In this cases, the declaration type can be replaced with
``auto`` improving readability and maintainability.
.. code-block:: c++
TypeName *my_pointer = new TypeName(my_param);
// becomes
auto *my_pointer = new TypeName(my_param);
The check will also replace the declaration type in multiple declarations, if
the following conditions are satisfied:
* All declared variables have the same type (i.e. all of them are pointers to
the same type).
* All declared variables are initialized with a ``new`` expression.
* The types of all the new expressions are the same than the pointee of the
declaration type.
.. code-block:: c++
TypeName *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
// becomes
auto *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
Cast expressions
----------------
Frequently, when a variable is declared and initialized with a cast, the
variable type is written twice: in the declaration type and in the
cast expression. In this cases, the declaration type can be replaced with
``auto`` improving readability and maintainability.
.. code-block:: c++
TypeName *my_pointer = static_cast<TypeName>(my_param);
// becomes
auto *my_pointer = static_cast<TypeName>(my_param);
The check handles ``static_cast``, ``dynamic_cast``, ``const_cast``,
``reinterpret_cast``, functional casts, C-style casts and function templates
that behave as casts, such as ``llvm::dyn_cast``, ``boost::lexical_cast`` and
``gsl::narrow_cast``. Calls to function templates are considered to behave as
casts if the first template argument is explicit and is a type, and the function
returns that type, or a pointer or reference to it.
Known Limitations
-----------------
* If the initializer is an explicit conversion constructor, the check will not
replace the type specifier even though it would be safe to do so.
* User-defined iterators are not handled at this time.
Options
-------
.. option:: MinTypeNameLength
If the option is set to non-zero (default `5`), the check will ignore type
names having a length less than the option value. The option affects
expressions only, not iterators.
Spaces between multi-lexeme type names (``long int``) are considered as one.
If the :option:`RemoveStars` option (see below) is set to `true`, then ``*s``
in the type are also counted as a part of the type name.
.. code-block:: c++
// MinTypeNameLength = 0, RemoveStars=0
int a = static_cast<int>(foo()); // ---> auto a = ...
// length(bool *) = 4
bool *b = new bool; // ---> auto *b = ...
unsigned c = static_cast<unsigned>(foo()); // ---> auto c = ...
// MinTypeNameLength = 5, RemoveStars=0
int a = static_cast<int>(foo()); // ---> int a = ...
bool b = static_cast<bool>(foo()); // ---> bool b = ...
bool *pb = static_cast<bool*>(foo()); // ---> bool *pb = ...
unsigned c = static_cast<unsigned>(foo()); // ---> auto c = ...
// length(long <on-or-more-spaces> int) = 8
long int d = static_cast<long int>(foo()); // ---> auto d = ...
// MinTypeNameLength = 5, RemoveStars=1
int a = static_cast<int>(foo()); // ---> int a = ...
// length(int * * ) = 5
int **pa = static_cast<int**>(foo()); // ---> auto pa = ...
bool b = static_cast<bool>(foo()); // ---> bool b = ...
bool *pb = static_cast<bool*>(foo()); // ---> auto pb = ...
unsigned c = static_cast<unsigned>(foo()); // ---> auto c = ...
long int d = static_cast<long int>(foo()); // ---> auto d = ...
.. option:: RemoveStars
If the option is set to `true` (default is `false`), the check will remove
stars from the non-typedef pointer types when replacing type names with
``auto``. Otherwise, the check will leave stars. For example:
.. code-block:: c++
TypeName *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
// RemoveStars = 0
auto *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
// RemoveStars = 1
auto my_first_pointer = new TypeName, my_second_pointer = new TypeName;
.. title:: clang-tidy - modernize-use-bool-literals
modernize-use-bool-literals
===========================
Finds integer literals which are cast to ``bool``.
.. code-block:: c++
bool p = 1;
bool f = static_cast<bool>(1);
std::ios_base::sync_with_stdio(0);
bool x = p ? 1 : 0;
// transforms to
bool p = true;
bool f = true;
std::ios_base::sync_with_stdio(false);
bool x = p ? true : false;
Options
-------
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. title:: clang-tidy - modernize-use-default-member-init
modernize-use-default-member-init
=================================
This check converts a default constructor's member initializers into the new
default member initializers in C++11. Other member initializers that match the
default member initializer are removed. This can reduce repeated code or allow
use of '= default'.
.. code-block:: c++
struct A {
A() : i(5), j(10.0) {}
A(int i) : i(i), j(10.0) {}
int i;
double j;
};
// becomes
struct A {
A() {}
A(int i) : i(i) {}
int i{5};
double j{10.0};
};
.. note::
Only converts member initializers for built-in types, enums, and pointers.
The `readability-redundant-member-init` check will remove redundant member
initializers for classes.
Options
-------
.. option:: UseAssignment
If this option is set to `true` (default is `false`), the check will initialise
members with an assignment. For example:
.. code-block:: c++
struct A {
A() {}
A(int i) : i(i) {}
int i = 5;
double j = 10.0;
};
.. option:: IgnoreMacros
If this option is set to `true` (default is `true`), the check will not warn
about members declared inside macros.
:orphan:
.. title:: clang-tidy - modernize-use-default
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-equals-default.html
modernize-use-default
=====================
This check has been renamed to
`modernize-use-equals-default <modernize-use-equals-default.html>`_.
.. title:: clang-tidy - modernize-use-emplace
modernize-use-emplace
=====================
The check flags insertions to an STL-style container done by calling the
``push_back`` method with an explicitly-constructed temporary of the container
element type. In this case, the corresponding ``emplace_back`` method
results in less verbose and potentially more efficient code.
Right now the check doesn't support ``push_front`` and ``insert``.
It also doesn't support ``insert`` functions for associative containers
because replacing ``insert`` with ``emplace`` may result in
`speed regression <https://htmlpreview.github.io/?https://github.com/HowardHinnant/papers/blob/master/insert_vs_emplace.html>`_, but it might get support with some addition flag in the future.
By default only ``std::vector``, ``std::deque``, ``std::list`` are considered.
This list can be modified using the :option:`ContainersWithPushBack` option.
Before:
.. code-block:: c++
std::vector<MyClass> v;
v.push_back(MyClass(21, 37));
std::vector<std::pair<int, int>> w;
w.push_back(std::pair<int, int>(21, 37));
w.push_back(std::make_pair(21L, 37L));
After:
.. code-block:: c++
std::vector<MyClass> v;
v.emplace_back(21, 37);
std::vector<std::pair<int, int>> w;
w.emplace_back(21, 37);
w.emplace_back(21L, 37L);
By default, the check is able to remove unnecessary ``std::make_pair`` and
``std::make_tuple`` calls from ``push_back`` calls on containers of
``std::pair`` and ``std::tuple``. Custom tuple-like types can be modified by
the :option:`TupleTypes` option; custom make functions can be modified by the
:option:`TupleMakeFunctions` option.
The other situation is when we pass arguments that will be converted to a type
inside a container.
Before:
.. code-block:: c++
std::vector<boost::optional<std::string> > v;
v.push_back("abc");
After:
.. code-block:: c++
std::vector<boost::optional<std::string> > v;
v.emplace_back("abc");
In some cases the transformation would be valid, but the code wouldn't be
exception safe. In this case the calls of ``push_back`` won't be replaced.
.. code-block:: c++
std::vector<std::unique_ptr<int>> v;
v.push_back(std::unique_ptr<int>(new int(0)));
auto *ptr = new int(1);
v.push_back(std::unique_ptr<int>(ptr));
This is because replacing it with ``emplace_back`` could cause a leak of this
pointer if ``emplace_back`` would throw exception before emplacement (e.g. not
enough memory to add a new element).
For more info read item 42 - "Consider emplacement instead of insertion." of
Scott Meyers "Effective Modern C++".
The default smart pointers that are considered are ``std::unique_ptr``,
``std::shared_ptr``, ``std::auto_ptr``. To specify other smart pointers or
other classes use the :option:`SmartPointers` option.
Check also doesn't fire if any argument of the constructor call would be:
- a bit-field (bit-fields can't bind to rvalue/universal reference)
- a ``new`` expression (to avoid leak)
- if the argument would be converted via derived-to-base cast.
This check requires C++11 or higher to run.
Options
-------
.. option:: ContainersWithPushBack
Semicolon-separated list of class names of custom containers that support
``push_back``.
.. option:: IgnoreImplicitConstructors
When `true`, the check will ignore implicitly constructed arguments of
``push_back``, e.g.
.. code-block:: c++
std::vector<std::string> v;
v.push_back("a"); // Ignored when IgnoreImplicitConstructors is `true`.
Default is `false`.
.. option:: SmartPointers
Semicolon-separated list of class names of custom smart pointers.
.. option:: TupleTypes
Semicolon-separated list of ``std::tuple``-like class names.
.. option:: TupleMakeFunctions
Semicolon-separated list of ``std::make_tuple``-like function names. Those
function calls will be removed from ``push_back`` calls and turned into
``emplace_back``.
Example
^^^^^^^
.. code-block:: c++
std::vector<MyTuple<int, bool, char>> x;
x.push_back(MakeMyTuple(1, false, 'x'));
transforms to:
.. code-block:: c++
std::vector<MyTuple<int, bool, char>> x;
x.emplace_back(1, false, 'x');
when :option:`TupleTypes` is set to ``MyTuple`` and :option:`TupleMakeFunctions`
is set to ``MakeMyTuple``.
.. title:: clang-tidy - modernize-use-equals-default
modernize-use-equals-default
============================
This check replaces default bodies of special member functions with ``=
default;``. The explicitly defaulted function declarations enable more
opportunities in optimization, because the compiler might treat explicitly
defaulted functions as trivial.
.. code-block:: c++
struct A {
A() {}
~A();
};
A::~A() {}
// becomes
struct A {
A() = default;
~A();
};
A::~A() = default;
.. note::
Move-constructor and move-assignment operator are not supported yet.
Options
-------
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. title:: clang-tidy - modernize-use-equals-delete
modernize-use-equals-delete
===========================
This check marks unimplemented private special member functions with ``= delete``.
To avoid false-positives, this check only applies in a translation unit that has
all other member functions implemented.
.. code-block:: c++
struct A {
private:
A(const A&);
A& operator=(const A&);
};
// becomes
struct A {
private:
A(const A&) = delete;
A& operator=(const A&) = delete;
};
.. option:: IgnoreMacros
If this option is set to `true` (default is `true`), the check will not warn
about functions declared inside macros.
.. title:: clang-tidy - modernize-use-nodiscard
modernize-use-nodiscard
=======================
Adds ``[[nodiscard]]`` attributes (introduced in C++17) to member functions in
order to highlight at compile time which return values should not be ignored.
Member functions need to satisfy the following conditions to be considered by
this check:
- no ``[[nodiscard]]``, ``[[noreturn]]``,
``__attribute__((warn_unused_result))``,
``[[clang::warn_unused_result]]`` nor ``[[gcc::warn_unused_result]]``
attribute,
- non-void return type,
- non-template return types,
- const member function,
- non-variadic functions,
- no non-const reference parameters,
- no pointer parameters,
- no template parameters,
- no template function parameters,
- not be a member of a class with mutable member variables,
- no Lambdas,
- no conversion functions.
Such functions have no means of altering any state or passing values other than
via the return type. Unless the member functions are altering state via some
external call (e.g. I/O).
Example
-------
.. code-block:: c++
bool empty() const;
bool empty(int i) const;
transforms to:
.. code-block:: c++
[[nodiscard]] bool empty() const;
[[nodiscard]] bool empty(int i) const;
Options
-------
.. option:: ReplacementString
Specifies a macro to use instead of ``[[nodiscard]]``. This is useful when
maintaining source code that needs to compile with a pre-C++17 compiler.
Example
^^^^^^^
.. code-block:: c++
bool empty() const;
bool empty(int i) const;
transforms to:
.. code-block:: c++
NO_DISCARD bool empty() const;
NO_DISCARD bool empty(int i) const;
if the :option:`ReplacementString` option is set to `NO_DISCARD`.
.. note::
If the :option:`ReplacementString` is not a C++ attribute, but instead a
macro, then that macro must be defined in scope or the fix-it will not be
applied.
.. note::
For alternative ``__attribute__`` syntax options to mark functions as
``[[nodiscard]]`` in non-c++17 source code.
See https://clang.llvm.org/docs/AttributeReference.html#nodiscard-warn-unused-result
.. title:: clang-tidy - modernize-use-noexcept
modernize-use-noexcept
======================
This check replaces deprecated dynamic exception specifications with
the appropriate noexcept specification (introduced in C++11). By
default this check will replace ``throw()`` with ``noexcept``,
and ``throw(<exception>[,...])`` or ``throw(...)`` with
``noexcept(false)``.
Example
-------
.. code-block:: c++
void foo() throw();
void bar() throw(int) {}
transforms to:
.. code-block:: c++
void foo() noexcept;
void bar() noexcept(false) {}
Options
-------
.. option:: ReplacementString
Users can use :option:`ReplacementString` to specify a macro to use
instead of ``noexcept``. This is useful when maintaining source code
that uses custom exception specification marking other than
``noexcept``. Fix-it hints will only be generated for non-throwing
specifications.
Example
^^^^^^^
.. code-block:: c++
void bar() throw(int);
void foo() throw();
transforms to:
.. code-block:: c++
void bar() throw(int); // No fix-it generated.
void foo() NOEXCEPT;
if the :option:`ReplacementString` option is set to `NOEXCEPT`.
.. option:: UseNoexceptFalse
Enabled by default, disabling will generate fix-it hints that remove
throwing dynamic exception specs, e.g., ``throw(<something>)``,
completely without providing a replacement text, except for
destructors and delete operators that are ``noexcept(true)`` by
default.
Example
^^^^^^^
.. code-block:: c++
void foo() throw(int) {}
struct bar {
void foobar() throw(int);
void operator delete(void *ptr) throw(int);
void operator delete[](void *ptr) throw(int);
~bar() throw(int);
}
transforms to:
.. code-block:: c++
void foo() {}
struct bar {
void foobar();
void operator delete(void *ptr) noexcept(false);
void operator delete[](void *ptr) noexcept(false);
~bar() noexcept(false);
}
if the :option:`UseNoexceptFalse` option is set to `false`.
.. title:: clang-tidy - modernize-use-nullptr
modernize-use-nullptr
=====================
The check converts the usage of null pointer constants (eg. ``NULL``, ``0``)
to use the new C++11 ``nullptr`` keyword.
Example
-------
.. code-block:: c++
void assignment() {
char *a = NULL;
char *b = 0;
char c = 0;
}
int *ret_ptr() {
return 0;
}
transforms to:
.. code-block:: c++
void assignment() {
char *a = nullptr;
char *b = nullptr;
char c = 0;
}
int *ret_ptr() {
return nullptr;
}
Options
-------
.. option:: NullMacros
Comma-separated list of macro names that will be transformed along with
``NULL``. By default this check will only replace the ``NULL`` macro and will
skip any similar user-defined macros.
Example
^^^^^^^
.. code-block:: c++
#define MY_NULL (void*)0
void assignment() {
void *p = MY_NULL;
}
transforms to:
.. code-block:: c++
#define MY_NULL NULL
void assignment() {
int *p = nullptr;
}
if the :option:`NullMacros` option is set to ``MY_NULL``.
.. title:: clang-tidy - modernize-use-override
modernize-use-override
======================
Adds ``override`` (introduced in C++11) to overridden virtual functions and
removes ``virtual`` from those functions as it is not required.
``virtual`` on non base class implementations was used to help indicate to the
user that a function was virtual. C++ compilers did not use the presence of
this to signify an overridden function.
In C++ 11 ``override`` and ``final`` keywords were introduced to allow
overridden functions to be marked appropriately. Their presence allows
compilers to verify that an overridden function correctly overrides a base
class implementation.
This can be useful as compilers can generate a compile time error when:
- The base class implementation function signature changes.
- The user has not created the override with the correct signature.
Options
-------
.. option:: IgnoreDestructors
If set to `true`, this check will not diagnose destructors. Default is `false`.
.. option:: AllowOverrideAndFinal
If set to `true`, this check will not diagnose ``override`` as redundant
with ``final``. This is useful when code will be compiled by a compiler with
warning/error checking flags requiring ``override`` explicitly on overridden
members, such as ``gcc -Wsuggest-override``/``gcc -Werror=suggest-override``.
Default is `false`.
.. option:: OverrideSpelling
Specifies a macro to use instead of ``override``. This is useful when
maintaining source code that also needs to compile with a pre-C++11
compiler.
.. option:: FinalSpelling
Specifies a macro to use instead of ``final``. This is useful when
maintaining source code that also needs to compile with a pre-C++11
compiler.
.. note::
For more information on the use of ``override`` see https://en.cppreference.com/w/cpp/language/override
.. title:: clang-tidy - modernize-use-trailing-return-type
modernize-use-trailing-return-type
==================================
Rewrites function signatures to use a trailing return type
(introduced in C++11). This transformation is purely stylistic.
The return type before the function name is replaced by ``auto``
and inserted after the function parameter list (and qualifiers).
Example
-------
.. code-block:: c++
int f1();
inline int f2(int arg) noexcept;
virtual float f3() const && = delete;
transforms to:
.. code-block:: c++
auto f1() -> int;
inline auto f2(int arg) -> int noexcept;
virtual auto f3() const && -> float = delete;
Known Limitations
-----------------
The following categories of return types cannot be rewritten currently:
* function pointers
* member function pointers
* member pointers
Unqualified names in the return type might erroneously refer to different entities after the rewrite.
Preventing such errors requires a full lookup of all unqualified names present in the return type in the scope of the trailing return type location.
This location includes e.g. function parameter names and members of the enclosing class (including all inherited classes).
Such a lookup is currently not implemented.
Given the following piece of code
.. code-block:: c++
struct S { long long value; };
S f(unsigned S) { return {S * 2}; }
class CC {
int S;
struct S m();
};
S CC::m() { return {0}; }
a careless rewrite would produce the following output:
.. code-block:: c++
struct S { long long value; };
auto f(unsigned S) -> S { return {S * 2}; } // error
class CC {
int S;
auto m() -> struct S;
};
auto CC::m() -> S { return {0}; } // error
This code fails to compile because the S in the context of f refers to the equally named function parameter.
Similarly, the S in the context of m refers to the equally named class member.
The check can currently only detect and avoid a clash with a function parameter name.
.. title:: clang-tidy - modernize-use-transparent-functors
modernize-use-transparent-functors
==================================
Prefer transparent functors to non-transparent ones. When using transparent
functors, the type does not need to be repeated. The code is easier to read,
maintain and less prone to errors. It is not possible to introduce unwanted
conversions.
.. code-block:: c++
// Non-transparent functor
std::map<int, std::string, std::greater<int>> s;
// Transparent functor.
std::map<int, std::string, std::greater<>> s;
// Non-transparent functor
using MyFunctor = std::less<MyType>;
It is not always a safe transformation though. The following case will be
untouched to preserve the semantics.
.. code-block:: c++
// Non-transparent functor
std::map<const char *, std::string, std::greater<std::string>> s;
Options
-------
.. option:: SafeMode
If the option is set to `true`, the check will not diagnose cases where
using a transparent functor cannot be guaranteed to produce identical results
as the original code. The default value for this option is `false`.
This check requires using C++14 or higher to run.
.. title:: clang-tidy - modernize-use-uncaught-exceptions
modernize-use-uncaught-exceptions
====================================
This check will warn on calls to ``std::uncaught_exception`` and replace them
with calls to ``std::uncaught_exceptions``, since ``std::uncaught_exception``
was deprecated in C++17.
Below are a few examples of what kind of occurrences will be found and what
they will be replaced with.
.. code-block:: c++
#define MACRO1 std::uncaught_exception
#define MACRO2 std::uncaught_exception
int uncaught_exception() {
return 0;
}
int main() {
int res;
res = uncaught_exception();
// No warning, since it is not the deprecated function from namespace std
res = MACRO2();
// Warning, but will not be replaced
res = std::uncaught_exception();
// Warning and replaced
using std::uncaught_exception;
// Warning and replaced
res = uncaught_exception();
// Warning and replaced
}
After applying the fixes the code will look like the following:
.. code-block:: c++
#define MACRO1 std::uncaught_exception
#define MACRO2 std::uncaught_exception
int uncaught_exception() {
return 0;
}
int main() {
int res;
res = uncaught_exception();
res = MACRO2();
res = std::uncaught_exceptions();
using std::uncaught_exceptions;
res = uncaught_exceptions();
}
.. title:: clang-tidy - modernize-use-using
modernize-use-using
===================
The check converts the usage of ``typedef`` with ``using`` keyword.
Before:
.. code-block:: c++
typedef int variable;
class Class{};
typedef void (Class::* MyPtrType)() const;
typedef struct { int a; } R_t, *R_p;
After:
.. code-block:: c++
using variable = int;
class Class{};
using MyPtrType = void (Class::*)() const;
using R_t = struct { int a; };
using R_p = R_t*;
This check requires using C++11 or higher to run.
Options
-------
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. title:: clang-tidy - mpi-buffer-deref
mpi-buffer-deref
================
This check verifies if a buffer passed to an MPI (Message Passing Interface)
function is sufficiently dereferenced. Buffers should be passed as a single
pointer or array. As MPI function signatures specify ``void *`` for their buffer
types, insufficiently dereferenced buffers can be passed, like for example as
double pointers or multidimensional arrays, without a compiler warning emitted.
Examples:
.. code-block:: c++
// A double pointer is passed to the MPI function.
char *buf;
MPI_Send(&buf, 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
// A multidimensional array is passed to the MPI function.
short buf[1][1];
MPI_Send(buf, 1, MPI_SHORT, 0, 0, MPI_COMM_WORLD);
// A pointer to an array is passed to the MPI function.
short *buf[1];
MPI_Send(buf, 1, MPI_SHORT, 0, 0, MPI_COMM_WORLD);
.. title:: clang-tidy - mpi-type-mismatch
mpi-type-mismatch
=================
This check verifies if buffer type and MPI (Message Passing Interface) datatype
pairs match for used MPI functions. All MPI datatypes defined by the MPI
standard (3.1) are verified by this check. User defined typedefs, custom MPI
datatypes and null pointer constants are skipped, in the course of verification.
Example:
.. code-block:: c++
// In this case, the buffer type matches MPI datatype.
char buf;
MPI_Send(&buf, 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
// In the following case, the buffer type does not match MPI datatype.
int buf;
MPI_Send(&buf, 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
.. title:: clang-tidy - objc-avoid-nserror-init
objc-avoid-nserror-init
=======================
Finds improper initialization of ``NSError`` objects.
According to Apple developer document, we should always use factory method
``errorWithDomain:code:userInfo:`` to create new NSError objects instead
of ``[NSError alloc] init]``. Otherwise it will lead to a warning message
during runtime.
The corresponding information about ``NSError`` creation: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html
.. title:: clang-tidy - objc-dealloc-in-category
objc-dealloc-in-category
========================
Finds implementations of ``-dealloc`` in Objective-C categories. The category
implementation will override any ``-dealloc`` in the class implementation,
potentially causing issues.
Classes implement ``-dealloc`` to perform important actions to deallocate
an object. If a category on the class implements ``-dealloc``, it will
override the class's implementation and unexpected deallocation behavior
may occur.
.. title:: clang-tidy - objc-forbidden-subclassing
objc-forbidden-subclassing
==========================
Finds Objective-C classes which are subclasses of classes which are not designed
to be subclassed.
By default, includes a list of Objective-C classes which are publicly documented
as not supporting subclassing.
.. note::
Instead of using this check, for code under your control, you should add
``__attribute__((objc_subclassing_restricted))`` before your ``@interface``
declarations to ensure the compiler prevents others from subclassing your
Objective-C classes.
See https://clang.llvm.org/docs/AttributeReference.html#objc-subclassing-restricted
Options
-------
.. option:: ForbiddenSuperClassNames
Semicolon-separated list of names of Objective-C classes which
do not support subclassing.
Defaults to `ABNewPersonViewController;ABPeoplePickerNavigationController;ABPersonViewController;ABUnknownPersonViewController;NSHashTable;NSMapTable;NSPointerArray;NSPointerFunctions;NSTimer;UIActionSheet;UIAlertView;UIImagePickerController;UITextInputMode;UIWebView`.
.. title:: clang-tidy - objc-missing-hash
objc-missing-hash
=================
Finds Objective-C implementations that implement ``-isEqual:`` without also
appropriately implementing ``-hash``.
Apple documentation highlights that objects that are equal must have the same
hash value:
https://developer.apple.com/documentation/objectivec/1418956-nsobject/1418795-isequal?language=objc
Note that the check only verifies the presence of ``-hash`` in scenarios where
its omission could result in unexpected behavior. The verification of the
implementation of ``-hash`` is the responsibility of the developer, e.g.,
through the addition of unit tests to verify the implementation.
.. title:: clang-tidy - objc-nsinvocation-argument-lifetime
objc-nsinvocation-argument-lifetime
===================================
Finds calls to ``NSInvocation`` methods under ARC that don't have proper
argument object lifetimes. When passing Objective-C objects as parameters
to the ``NSInvocation`` methods ``getArgument:atIndex:`` and
``getReturnValue:``, the values are copied by value into the argument pointer,
which leads to to incorrect releasing behavior if the object pointers are
not declared ``__unsafe_unretained``.
For code:
.. code-block:: objc
id arg;
[invocation getArgument:&arg atIndex:2];
__strong id returnValue;
[invocation getReturnValue:&returnValue];
The fix will be:
.. code-block:: objc
__unsafe_unretained id arg;
[invocation getArgument:&arg atIndex:2];
__unsafe_unretained id returnValue;
[invocation getReturnValue:&returnValue];
The check will warn on being passed instance variable references that have
lifetimes other than ``__unsafe_unretained``, but does not propose a fix:
.. code-block:: objc
// "id _returnValue" is declaration of instance variable of class.
[invocation getReturnValue:&self->_returnValue];
.. title:: clang-tidy - objc-property-declaration
objc-property-declaration
=========================
Finds property declarations in Objective-C files that do not follow the pattern
of property names in Apple's programming guide. The property name should be
in the format of Lower Camel Case.
For code:
.. code-block:: objc
@property(nonatomic, assign) int LowerCamelCase;
The fix will be:
.. code-block:: objc
@property(nonatomic, assign) int lowerCamelCase;
The check will only fix 'CamelCase' to 'camelCase'. In some other cases we will
only provide warning messages since the property name could be complicated.
Users will need to come up with a proper name by their own.
This check also accepts special acronyms as prefixes or suffixes. Such prefixes or suffixes
will suppress the Lower Camel Case check according to the guide:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html#//apple_ref/doc/uid/20001281-1002931-BBCFHEAB
For a full list of well-known acronyms:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/APIAbbreviations.html#//apple_ref/doc/uid/20001285-BCIHCGAE
The corresponding style rule: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-1001757
The check will also accept property declared in category with a prefix of
lowercase letters followed by a '_' to avoid naming conflict. For example:
.. code-block:: objc
@property(nonatomic, assign) int abc_lowerCamelCase;
The corresponding style rule: https://developer.apple.com/library/content/qa/qa1908/_index.html
.. title:: clang-tidy - objc-super-self
objc-super-self
===============
Finds invocations of ``-self`` on super instances in initializers of subclasses
of ``NSObject`` and recommends calling a superclass initializer instead.
Invoking ``-self`` on super instances in initializers is a common programmer
error when the programmer's original intent is to call a superclass
initializer. Failing to call a superclass initializer breaks initializer
chaining and can result in invalid object initialization.
.. title:: clang-tidy - openmp-exception-escape
openmp-exception-escape
=======================
Analyzes OpenMP Structured Blocks and checks that no exception escapes
out of the Structured Block it was thrown in.
As per the OpenMP specification, a structured block is an executable statement,
possibly compound, with a single entry at the top and a single exit at the
bottom. Which means, ``throw`` may not be used to to 'exit' out of the
structured block. If an exception is not caught in the same structured block
it was thrown in, the behaviour is undefined.
FIXME: this check does not model SEH, ``setjmp``/``longjmp``.
WARNING! This check may be expensive on large source files.
Options
-------
.. option:: IgnoredExceptions
Comma-separated list containing type names which are not counted as thrown
exceptions in the check. Default value is an empty string.
.. title:: clang-tidy - openmp-use-default-none
openmp-use-default-none
=======================
Finds OpenMP directives that are allowed to contain a ``default`` clause,
but either don't specify it or the clause is specified but with the kind
other than ``none``, and suggests to use the ``default(none)`` clause.
Using ``default(none)`` clause forces developers to explicitly specify data
sharing attributes for the variables referenced in the construct,
thus making it obvious which variables are referenced, and what is their
data sharing attribute, thus increasing readability and possibly making errors
easier to spot.
Example
-------
.. code-block:: c++
// ``for`` directive can not have ``default`` clause, no diagnostics.
void n0(const int a) {
#pragma omp for
for (int b = 0; b < a; b++)
;
}
// ``parallel`` directive.
// ``parallel`` directive can have ``default`` clause, but said clause is not
// specified, diagnosed.
void p0_0() {
#pragma omp parallel
;
// WARNING: OpenMP directive ``parallel`` does not specify ``default``
// clause. Consider specifying ``default(none)`` clause.
}
// ``parallel`` directive can have ``default`` clause, and said clause is
// specified, with ``none`` kind, all good.
void p0_1() {
#pragma omp parallel default(none)
;
}
// ``parallel`` directive can have ``default`` clause, and said clause is
// specified, but with ``shared`` kind, which is not ``none``, diagnose.
void p0_2() {
#pragma omp parallel default(shared)
;
// WARNING: OpenMP directive ``parallel`` specifies ``default(shared)``
// clause. Consider using ``default(none)`` clause instead.
}
// ``parallel`` directive can have ``default`` clause, and said clause is
// specified, but with ``firstprivate`` kind, which is not ``none``, diagnose.
void p0_3() {
#pragma omp parallel default(firstprivate)
;
// WARNING: OpenMP directive ``parallel`` specifies ``default(firstprivate)``
// clause. Consider using ``default(none)`` clause instead.
}
.. title:: clang-tidy - abseil-duration-addition
abseil-duration-addition
========================
Check for cases where addition should be performed in the ``absl::Time`` domain.
When adding two values, and one is known to be an ``absl::Time``, we can infer
that the other should be interpreted as an ``absl::Duration`` of a similar
scale, and make that inference explicit.
Examples:
.. code-block:: c++
// Original - Addition in the integer domain
int x;
absl::Time t;
int result = absl::ToUnixSeconds(t) + x;
// Suggestion - Addition in the absl::Time domain
int result = absl::ToUnixSeconds(t + absl::Seconds(x));
.. title:: clang-tidy - abseil-duration-comparison
abseil-duration-comparison
==========================
Checks for comparisons which should be in the ``absl::Duration`` domain instead
of the floating point or integer domains.
N.B.: In cases where a ``Duration`` was being converted to an integer and then
compared against a floating-point value, truncation during the ``Duration``
conversion might yield a different result. In practice this is very rare, and
still indicates a bug which should be fixed.
Examples:
.. code-block:: c++
// Original - Comparison in the floating point domain
double x;
absl::Duration d;
if (x < absl::ToDoubleSeconds(d)) ...
// Suggested - Compare in the absl::Duration domain instead
if (absl::Seconds(x) < d) ...
// Original - Comparison in the integer domain
int x;
absl::Duration d;
if (x < absl::ToInt64Microseconds(d)) ...
// Suggested - Compare in the absl::Duration domain instead
if (absl::Microseconds(x) < d) ...
.. title:: clang-tidy - abseil-duration-conversion-cast
abseil-duration-conversion-cast
===============================
Checks for casts of ``absl::Duration`` conversion functions, and recommends
the right conversion function instead.
Examples:
.. code-block:: c++
// Original - Cast from a double to an integer
absl::Duration d;
int i = static_cast<int>(absl::ToDoubleSeconds(d));
// Suggested - Use the integer conversion function directly.
int i = absl::ToInt64Seconds(d);
// Original - Cast from a double to an integer
absl::Duration d;
double x = static_cast<double>(absl::ToInt64Seconds(d));
// Suggested - Use the integer conversion function directly.
double x = absl::ToDoubleSeconds(d);
Note: In the second example, the suggested fix could yield a different result,
as the conversion to integer could truncate. In practice, this is very rare,
and you should use ``absl::Trunc`` to perform this operation explicitly instead.
.. title:: clang-tidy - abseil-duration-division
abseil-duration-division
========================
``absl::Duration`` arithmetic works like it does with integers. That means that
division of two ``absl::Duration`` objects returns an ``int64`` with any fractional
component truncated toward 0. See `this link <https://github.com/abseil/abseil-cpp/blob/29ff6d4860070bf8fcbd39c8805d0c32d56628a3/absl/time/time.h#L137>`_ for more information on arithmetic with ``absl::Duration``.
For example:
.. code-block:: c++
absl::Duration d = absl::Seconds(3.5);
int64 sec1 = d / absl::Seconds(1); // Truncates toward 0.
int64 sec2 = absl::ToInt64Seconds(d); // Equivalent to division.
assert(sec1 == 3 && sec2 == 3);
double dsec = d / absl::Seconds(1); // WRONG: Still truncates toward 0.
assert(dsec == 3.0);
If you want floating-point division, you should use either the
``absl::FDivDuration()`` function, or one of the unit conversion functions such
as ``absl::ToDoubleSeconds()``. For example:
.. code-block:: c++
absl::Duration d = absl::Seconds(3.5);
double dsec1 = absl::FDivDuration(d, absl::Seconds(1)); // GOOD: No truncation.
double dsec2 = absl::ToDoubleSeconds(d); // GOOD: No truncation.
assert(dsec1 == 3.5 && dsec2 == 3.5);
This check looks for uses of ``absl::Duration`` division that is done in a
floating-point context, and recommends the use of a function that returns a
floating-point value.
.. title:: clang-tidy - abseil-duration-factory-float
abseil-duration-factory-float
=============================
Checks for cases where the floating-point overloads of various
``absl::Duration`` factory functions are called when the more-efficient
integer versions could be used instead.
This check will not suggest fixes for literals which contain fractional
floating point values or non-literals. It will suggest removing
superfluous casts.
Examples:
.. code-block:: c++
// Original - Providing a floating-point literal.
absl::Duration d = absl::Seconds(10.0);
// Suggested - Use an integer instead.
absl::Duration d = absl::Seconds(10);
// Original - Explicitly casting to a floating-point type.
absl::Duration d = absl::Seconds(static_cast<double>(10));
// Suggested - Remove the explicit cast
absl::Duration d = absl::Seconds(10);
.. title:: clang-tidy - abseil-duration-factory-scale
abseil-duration-factory-scale
=============================
Checks for cases where arguments to ``absl::Duration`` factory functions are
scaled internally and could be changed to a different factory function. This
check also looks for arguments with a zero value and suggests using
``absl::ZeroDuration()`` instead.
Examples:
.. code-block:: c++
// Original - Internal multiplication.
int x;
absl::Duration d = absl::Seconds(60 * x);
// Suggested - Use absl::Minutes instead.
absl::Duration d = absl::Minutes(x);
// Original - Internal division.
int y;
absl::Duration d = absl::Milliseconds(y / 1000.);
// Suggested - Use absl:::Seconds instead.
absl::Duration d = absl::Seconds(y);
// Original - Zero-value argument.
absl::Duration d = absl::Hours(0);
// Suggested = Use absl::ZeroDuration instead
absl::Duration d = absl::ZeroDuration();
.. title:: clang-tidy - abseil-duration-subtraction
abseil-duration-subtraction
===========================
Checks for cases where subtraction should be performed in the
``absl::Duration`` domain. When subtracting two values, and the first one is
known to be a conversion from ``absl::Duration``, we can infer that the second
should also be interpreted as an ``absl::Duration``, and make that inference
explicit.
Examples:
.. code-block:: c++
// Original - Subtraction in the double domain
double x;
absl::Duration d;
double result = absl::ToDoubleSeconds(d) - x;
// Suggestion - Subtraction in the absl::Duration domain instead
double result = absl::ToDoubleSeconds(d - absl::Seconds(x));
// Original - Subtraction of two Durations in the double domain
absl::Duration d1, d2;
double result = absl::ToDoubleSeconds(d1) - absl::ToDoubleSeconds(d2);
// Suggestion - Subtraction in the absl::Duration domain instead
double result = absl::ToDoubleSeconds(d1 - d2);
Note: As with other ``clang-tidy`` checks, it is possible that multiple fixes
may overlap (as in the case of nested expressions), so not all occurrences can
be transformed in one run. In particular, this may occur for nested subtraction
expressions. Running ``clang-tidy`` multiple times will find and fix these
overlaps.
.. title:: clang-tidy - abseil-duration-unnecessary-conversion
abseil-duration-unnecessary-conversion
======================================
Finds and fixes cases where ``absl::Duration`` values are being converted to
numeric types and back again.
Floating-point examples:
.. code-block:: c++
// Original - Conversion to double and back again
absl::Duration d1;
absl::Duration d2 = absl::Seconds(absl::ToDoubleSeconds(d1));
// Suggestion - Remove unnecessary conversions
absl::Duration d2 = d1;
// Original - Division to convert to double and back again
absl::Duration d2 = absl::Seconds(absl::FDivDuration(d1, absl::Seconds(1)));
// Suggestion - Remove division and conversion
absl::Duration d2 = d1;
Integer examples:
.. code-block:: c++
// Original - Conversion to integer and back again
absl::Duration d1;
absl::Duration d2 = absl::Hours(absl::ToInt64Hours(d1));
// Suggestion - Remove unnecessary conversions
absl::Duration d2 = d1;
// Original - Integer division followed by conversion
absl::Duration d2 = absl::Seconds(d1 / absl::Seconds(1));
// Suggestion - Remove division and conversion
absl::Duration d2 = d1;
Unwrapping scalar operations:
.. code-block:: c++
// Original - Multiplication by a scalar
absl::Duration d1;
absl::Duration d2 = absl::Seconds(absl::ToInt64Seconds(d1) * 2);
// Suggestion - Remove unnecessary conversion
absl::Duration d2 = d1 * 2;
Note: Converting to an integer and back to an ``absl::Duration`` might be a
truncating operation if the value is not aligned to the scale of conversion.
In the rare case where this is the intended result, callers should use
``absl::Trunc`` to truncate explicitly.
.. title:: clang-tidy - abseil-faster-strsplit-delimiter
abseil-faster-strsplit-delimiter
================================
Finds instances of ``absl::StrSplit()`` or ``absl::MaxSplits()`` where the
delimiter is a single character string literal and replaces with a character.
The check will offer a suggestion to change the string literal into a character.
It will also catch code using ``absl::ByAnyChar()`` for just a single character
and will transform that into a single character as well.
These changes will give the same result, but using characters rather than
single character string literals is more efficient and readable.
Examples:
.. code-block:: c++
// Original - the argument is a string literal.
for (auto piece : absl::StrSplit(str, "B")) {
// Suggested - the argument is a character, which causes the more efficient
// overload of absl::StrSplit() to be used.
for (auto piece : absl::StrSplit(str, 'B')) {
// Original - the argument is a string literal inside absl::ByAnyChar call.
for (auto piece : absl::StrSplit(str, absl::ByAnyChar("B"))) {
// Suggested - the argument is a character, which causes the more efficient
// overload of absl::StrSplit() to be used and we do not need absl::ByAnyChar
// anymore.
for (auto piece : absl::StrSplit(str, 'B')) {
// Original - the argument is a string literal inside absl::MaxSplits call.
for (auto piece : absl::StrSplit(str, absl::MaxSplits("B", 1))) {
// Suggested - the argument is a character, which causes the more efficient
// overload of absl::StrSplit() to be used.
for (auto piece : absl::StrSplit(str, absl::MaxSplits('B', 1))) {
subl.. title:: clang-tidy - abseil-no-internal-dependencies
abseil-no-internal-dependencies
===============================
Warns if code using Abseil depends on internal details. If something is in a
namespace that includes the word “internal”, code is not allowed to depend upon
it beaucse it’s an implementation detail. They cannot friend it, include it,
you mention it or refer to it in any way. Doing so violates Abseil's
compatibility guidelines and may result in breakage. See
https://abseil.io/about/compatibility for more information.
The following cases will result in warnings:
.. code-block:: c++
absl::strings_internal::foo();
// warning triggered on this line
class foo {
friend struct absl::container_internal::faa;
// warning triggered on this line
};
absl::memory_internal::MakeUniqueResult();
// warning triggered on this line
.. title:: clang-tidy - abseil-no-namespace
abseil-no-namespace
===================
Ensures code does not open ``namespace absl`` as that violates Abseil's
compatibility guidelines. Code should not open ``namespace absl`` as that
conflicts with Abseil's compatibility guidelines and may result in breakage.
Any code that uses:
.. code-block:: c++
namespace absl {
...
}
will be prompted with a warning.
See `the full Abseil compatibility guidelines <https://
abseil.io/about/compatibility>`_ for more information.
.. title:: clang-tidy - abseil-redundant-strcat-calls
abseil-redundant-strcat-calls
=============================
Suggests removal of unnecessary calls to ``absl::StrCat`` when the result is
being passed to another call to ``absl::StrCat`` or ``absl::StrAppend``.
The extra calls cause unnecessary temporary strings to be constructed. Removing
them makes the code smaller and faster.
Examples:
.. code-block:: c++
std::string s = absl::StrCat("A", absl::StrCat("B", absl::StrCat("C", "D")));
//before
std::string s = absl::StrCat("A", "B", "C", "D");
//after
absl::StrAppend(&s, absl::StrCat("E", "F", "G"));
//before
absl::StrAppend(&s, "E", "F", "G");
//after
.. title:: clang-tidy - abseil-str-cat-append
abseil-str-cat-append
=====================
Flags uses of ``absl::StrCat()`` to append to a ``std::string``. Suggests
``absl::StrAppend()`` should be used instead.
The extra calls cause unnecessary temporary strings to be constructed. Removing
them makes the code smaller and faster.
.. code-block:: c++
a = absl::StrCat(a, b); // Use absl::StrAppend(&a, b) instead.
Does not diagnose cases where ``absl::StrCat()`` is used as a template
argument for a functor.
.. title:: clang-tidy - abseil-string-find-startswith
abseil-string-find-startswith
=============================
Checks whether a ``std::string::find()`` result is compared with 0, and
suggests replacing with ``absl::StartsWith()``. This is both a readability and
performance issue.
.. code-block:: c++
string s = "...";
if (s.find("Hello World") == 0) { /* do something */ }
becomes
.. code-block:: c++
string s = "...";
if (absl::StartsWith(s, "Hello World")) { /* do something */ }
Options
-------
.. option:: StringLikeClasses
Semicolon-separated list of names of string-like classes. By default only
``std::basic_string`` is considered. The list of methods to considered is
fixed.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: AbseilStringsMatchHeader
The location of Abseil's ``strings/match.h``. Defaults to
``absl/strings/match.h``.
.. title:: clang-tidy - abseil-string-find-str-contains
abseil-string-find-str-contains
===============================
Finds ``s.find(...) == string::npos`` comparisons (for various string-like types)
and suggests replacing with ``absl::StrContains()``.
This improves readability and reduces the likelihood of accidentally mixing
``find()`` and ``npos`` from different string-like types.
By default, "string-like types" includes ``::std::basic_string``,
``::std::basic_string_view``, and ``::absl::string_view``. See the
StringLikeClasses option to change this.
.. code-block:: c++
std::string s = "...";
if (s.find("Hello World") == std::string::npos) { /* do something */ }
absl::string_view a = "...";
if (absl::string_view::npos != a.find("Hello World")) { /* do something */ }
becomes
.. code-block:: c++
std::string s = "...";
if (!absl::StrContains(s, "Hello World")) { /* do something */ }
absl::string_view a = "...";
if (absl::StrContains(a, "Hello World")) { /* do something */ }
Options
-------
.. option:: StringLikeClasses
Semicolon-separated list of names of string-like classes. By default includes
``::std::basic_string``, ``::std::basic_string_view``, and
``::absl::string_view``.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: AbseilStringsMatchHeader
The location of Abseil's ``strings/match.h``. Defaults to
``absl/strings/match.h``.
.. title:: clang-tidy - abseil-time-comparison
abseil-time-comparison
======================
Prefer comparisons in the ``absl::Time`` domain instead of the integer domain.
N.B.: In cases where an ``absl::Time`` is being converted to an integer,
alignment may occur. If the comparison depends on this alignment, doing the
comparison in the ``absl::Time`` domain may yield a different result. In
practice this is very rare, and still indicates a bug which should be fixed.
Examples:
.. code-block:: c++
// Original - Comparison in the integer domain
int x;
absl::Time t;
if (x < absl::ToUnixSeconds(t)) ...
// Suggested - Compare in the absl::Time domain instead
if (absl::FromUnixSeconds(x) < t) ...
.. title:: clang-tidy - abseil-time-subtraction
abseil-time-subtraction
=======================
Finds and fixes ``absl::Time`` subtraction expressions to do subtraction
in the Time domain instead of the numeric domain.
There are two cases of Time subtraction in which deduce additional type
information:
- When the result is an ``absl::Duration`` and the first argument is an
``absl::Time``.
- When the second argument is a ``absl::Time``.
In the first case, we must know the result of the operation, since without that
the second operand could be either an ``absl::Time`` or an ``absl::Duration``.
In the second case, the first operand *must* be an ``absl::Time``, because
subtracting an ``absl::Time`` from an ``absl::Duration`` is not defined.
Examples:
.. code-block:: c++
int x;
absl::Time t;
// Original - absl::Duration result and first operand is a absl::Time.
absl::Duration d = absl::Seconds(absl::ToUnixSeconds(t) - x);
// Suggestion - Perform subtraction in the Time domain instead.
absl::Duration d = t - absl::FromUnixSeconds(x);
// Original - Second operand is an absl::Time.
int i = x - absl::ToUnixSeconds(t);
// Suggestion - Perform subtraction in the Time domain instead.
int i = absl::ToInt64Seconds(absl::FromUnixSeconds(x) - t);
.. title:: clang-tidy - abseil-upgrade-duration-conversions
abseil-upgrade-duration-conversions
===================================
Finds calls to ``absl::Duration`` arithmetic operators and factories whose
argument needs an explicit cast to continue compiling after upcoming API
changes.
The operators ``*=``, ``/=``, ``*``, and ``/`` for ``absl::Duration`` currently
accept an argument of class type that is convertible to an arithmetic type. Such
a call currently converts the value to an ``int64_t``, even in a case such as
``std::atomic<float>`` that would result in lossy conversion.
Additionally, the ``absl::Duration`` factory functions (``absl::Hours``,
``absl::Minutes``, etc) currently accept an ``int64_t`` or a floating-point
type. Similar to the arithmetic operators, calls with an argument of class type
that is convertible to an arithmetic type go through the ``int64_t`` path.
These operators and factories will be changed to only accept arithmetic types to
prevent unintended behavior. After these changes are released, passing an
argument of class type will no longer compile, even if the type is implicitly
convertible to an arithmetic type.
Here are example fixes created by this check:
.. code-block:: c++
std::atomic<int> a;
absl::Duration d = absl::Milliseconds(a);
d *= a;
becomes
.. code-block:: c++
std::atomic<int> a;
absl::Duration d = absl::Milliseconds(static_cast<int64_t>(a));
d *= static_cast<int64_t>(a);
Note that this check always adds a cast to ``int64_t`` in order to preserve the
current behavior of user code. It is possible that this uncovers unintended
behavior due to types implicitly convertible to a floating-point type.
.. title:: clang-tidy - altera-id-dependent-backward-branch
altera-id-dependent-backward-branch
===================================
Finds ID-dependent variables and fields that are used within loops. This causes
branches to occur inside the loops, and thus leads to performance degradation.
.. code-block:: c++
// The following code will produce a warning because this ID-dependent
// variable is used in a loop condition statement.
int ThreadID = get_local_id(0);
// The following loop will produce a warning because the loop condition
// statement depends on an ID-dependent variable.
for (int i = 0; i < ThreadID; ++i) {
std::cout << i << std::endl;
}
// The following loop will not produce a warning, because the ID-dependent
// variable is not used in the loop condition statement.
for (int i = 0; i < 100; ++i) {
std::cout << ThreadID << std::endl;
}
Based on the `Altera SDK for OpenCL: Best Practices Guide
<https://www.altera.com/en_US/pdfs/literature/hb/opencl-sdk/aocl_optimization_guide.pdf>`_.
.. title:: clang-tidy - altera-kernel-name-restriction
altera-kernel-name-restriction
==============================
Finds kernel files and include directives whose filename is `kernel.cl`,
`Verilog.cl`, or `VHDL.cl`. The check is case insensitive.
Such kernel file names cause the offline compiler to generate intermediate
design files that have the same names as certain internal files, which
leads to a compilation error.
Based on the `Guidelines for Naming the Kernel` section in the
`Intel FPGA SDK for OpenCL Pro Edition: Programming Guide
<https://www.intel.com/content/www/us/en/programmable/documentation/mwh1391807965224.html#ewa1412973930963>`_.
.. title:: clang-tidy - altera-single-work-item-barrier
altera-single-work-item-barrier
===============================
Finds OpenCL kernel functions that call a barrier function but do not call
an ID function (``get_local_id``, ``get_local_id``, ``get_group_id``, or
``get_local_linear_id``).
These kernels may be viable single work-item kernels, but will be forced to
execute as NDRange kernels if using a newer version of the Altera Offline
Compiler (>= v17.01).
If using an older version of the Altera Offline Compiler, these kernel
functions will be treated as single work-item kernels, which could be
inefficient or lead to errors if NDRange semantics were intended.
Based on the `Altera SDK for OpenCL: Best Practices Guide
<https://www.altera.com/en_US/pdfs/literature/hb/opencl-sdk/aocl_optimization_guide.pdf>`_.
Examples:
.. code-block:: c++
// error: function calls barrier but does not call an ID function.
void __kernel barrier_no_id(__global int * foo, int size) {
for (int i = 0; i < 100; i++) {
foo[i] += 5;
}
barrier(CLK_GLOBAL_MEM_FENCE);
}
// ok: function calls barrier and an ID function.
void __kernel barrier_with_id(__global int * foo, int size) {
for (int i = 0; i < 100; i++) {
int tid = get_global_id(0);
foo[tid] += 5;
}
barrier(CLK_GLOBAL_MEM_FENCE);
}
// ok with AOC Version 17.01: the reqd_work_group_size turns this into
// an NDRange.
__attribute__((reqd_work_group_size(2,2,2)))
void __kernel barrier_with_id(__global int * foo, int size) {
for (int i = 0; i < 100; i++) {
foo[tid] += 5;
}
barrier(CLK_GLOBAL_MEM_FENCE);
}
Options
-------
.. option:: AOCVersion
Defines the version of the Altera Offline Compiler. Defaults to ``1600``
(corresponding to version 16.00).
.. title:: clang-tidy - altera-struct-pack-align
altera-struct-pack-align
========================
Finds structs that are inefficiently packed or aligned, and recommends
packing and/or aligning of said structs as needed.
Structs that are not packed take up more space than they should, and accessing
structs that are not well aligned is inefficient.
Fix-its are provided to fix both of these issues by inserting and/or amending
relevant struct attributes.
Based on the `Altera SDK for OpenCL: Best Practices Guide
<https://www.altera.com/en_US/pdfs/literature/hb/opencl-sdk/aocl_optimization_guide.pdf>`_.
.. code-block:: c++
// The following struct is originally aligned to 4 bytes, and thus takes up
// 12 bytes of memory instead of 10. Packing the struct will make it use
// only 10 bytes of memory, and aligning it to 16 bytes will make it
// efficient to access.
struct example {
char a; // 1 byte
double b; // 8 bytes
char c; // 1 byte
};
// The following struct is arranged in such a way that packing is not needed.
// However, it is aligned to 4 bytes instead of 8, and thus needs to be
// explicitly aligned.
struct implicitly_packed_example {
char a; // 1 byte
char b; // 1 byte
char c; // 1 byte
char d; // 1 byte
int e; // 4 bytes
};
// The following struct is explicitly aligned and packed.
struct good_example {
char a; // 1 byte
double b; // 8 bytes
char c; // 1 byte
} __attribute__((packed)) __attribute__((aligned(16));
// Explicitly aligning a struct to the wrong value will result in a warning.
// The following example should be aligned to 16 bytes, not 32.
struct badly_aligned_example {
char a; // 1 byte
double b; // 8 bytes
char c; // 1 byte
} __attribute__((packed)) __attribute__((aligned(32)));
.. title:: clang-tidy - altera-unroll-loops
altera-unroll-loops
===================
Finds inner loops that have not been unrolled, as well as fully unrolled loops
with unknown loop bounds or a large number of iterations.
Unrolling inner loops could improve the performance of OpenCL kernels. However,
if they have unknown loop bounds or a large number of iterations, they cannot
be fully unrolled, and should be partially unrolled.
Notes:
- This check is unable to determine the number of iterations in a ``while`` or
``do..while`` loop; hence if such a loop is fully unrolled, a note is emitted
advising the user to partially unroll instead.
- In ``for`` loops, our check only works with simple arithmetic increments (
``+``, ``-``, ``*``, ``/``). For all other increments, partial unrolling is
advised.
- Depending on the exit condition, the calculations for determining if the
number of iterations is large may be off by 1. This should not be an issue
since the cut-off is generally arbitrary.
Based on the `Altera SDK for OpenCL: Best Practices Guide
<https://www.altera.com/en_US/pdfs/literature/hb/opencl-sdk/aocl_optimization_guide.pdf>`_.
.. code-block:: c++
for (int i = 0; i < 10; i++) { // ok: outer loops should not be unrolled
int j = 0;
do { // warning: this inner do..while loop should be unrolled
j++;
} while (j < 15);
int k = 0;
#pragma unroll
while (k < 20) { // ok: this inner loop is already unrolled
k++;
}
}
int A[1000];
#pragma unroll
// warning: this loop is large and should be partially unrolled
for (int a : A) {
printf("%d", a);
}
#pragma unroll 5
// ok: this loop is large, but is partially unrolled
for (int a : A) {
printf("%d", a);
}
#pragma unroll
// warning: this loop is large and should be partially unrolled
for (int i = 0; i < 1000; ++i) {
printf("%d", i);
}
#pragma unroll 5
// ok: this loop is large, but is partially unrolled
for (int i = 0; i < 1000; ++i) {
printf("%d", i);
}
#pragma unroll
// warning: << operator not supported, recommend partial unrolling
for (int i = 0; i < 1000; i<<1) {
printf("%d", i);
}
std::vector<int> someVector (100, 0);
int i = 0;
#pragma unroll
// note: loop may be large, recommend partial unrolling
while (i < someVector.size()) {
someVector[i]++;
}
#pragma unroll
// note: loop may be large, recommend partial unrolling
while (true) {
printf("In loop");
}
#pragma unroll 5
// ok: loop may be large, but is partially unrolled
while (i < someVector.size()) {
someVector[i]++;
}
Options
-------
.. option:: MaxLoopIterations
Defines the maximum number of loop iterations that a fully unrolled loop
can have. By default, it is set to `100`.
In practice, this refers to the integer value of the upper bound
within the loop statement's condition expression.
.. title:: clang-tidy - android-cloexec-accept
android-cloexec-accept
======================
The usage of ``accept()`` is not recommended, it's better to use ``accept4()``.
Without this flag, an opened sensitive file descriptor would remain open across
a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
accept(sockfd, addr, addrlen);
// becomes
accept4(sockfd, addr, addrlen, SOCK_CLOEXEC);
.. title:: clang-tidy - android-cloexec-accept4
android-cloexec-accept4
=======================
``accept4()`` should include ``SOCK_CLOEXEC`` in its type argument to avoid the
file descriptor leakage. Without this flag, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
accept4(sockfd, addr, addrlen, SOCK_NONBLOCK);
// becomes
accept4(sockfd, addr, addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC);
.. title:: clang-tidy - android-cloexec-creat
android-cloexec-creat
=====================
The usage of ``creat()`` is not recommended, it's better to use ``open()``.
Examples:
.. code-block:: c++
int fd = creat(path, mode);
// becomes
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, mode);
.. title:: clang-tidy - android-cloexec-dup
android-cloexec-dup
===================
The usage of ``dup()`` is not recommended, it's better to use ``fcntl()``,
which can set the close-on-exec flag. Otherwise, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
int fd = dup(oldfd);
// becomes
int fd = fcntl(oldfd, F_DUPFD_CLOEXEC);
.. title:: clang-tidy - android-cloexec-epoll-create
android-cloexec-epoll-create
============================
The usage of ``epoll_create()`` is not recommended, it's better to use
``epoll_create1()``, which allows close-on-exec.
Examples:
.. code-block:: c++
epoll_create(size);
// becomes
epoll_create1(EPOLL_CLOEXEC);
.. title:: clang-tidy - android-cloexec-epoll-create1
android-cloexec-epoll-create1
=============================
``epoll_create1()`` should include ``EPOLL_CLOEXEC`` in its type argument to
avoid the file descriptor leakage. Without this flag, an opened sensitive file
would remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
epoll_create1(0);
// becomes
epoll_create1(EPOLL_CLOEXEC);
.. title:: clang-tidy - android-cloexec-fopen
android-cloexec-fopen
=====================
``fopen()`` should include ``e`` in their mode string; so ``re`` would be
valid. This is equivalent to having set ``FD_CLOEXEC on`` that descriptor.
Examples:
.. code-block:: c++
fopen("fn", "r");
// becomes
fopen("fn", "re");
.. title:: clang-tidy - android-cloexec-inotify-init
android-cloexec-inotify-init
============================
The usage of ``inotify_init()`` is not recommended, it's better to use
``inotify_init1()``.
Examples:
.. code-block:: c++
inotify_init();
// becomes
inotify_init1(IN_CLOEXEC);
.. title:: clang-tidy - android-cloexec-inotify-init1
android-cloexec-inotify-init1
=============================
``inotify_init1()`` should include ``IN_CLOEXEC`` in its type argument to avoid the
file descriptor leakage. Without this flag, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
inotify_init1(IN_NONBLOCK);
// becomes
inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
.. title:: clang-tidy - android-cloexec-memfd-create
android-cloexec-memfd-create
============================
``memfd_create()`` should include ``MFD_CLOEXEC`` in its type argument to avoid
the file descriptor leakage. Without this flag, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
memfd_create(name, MFD_ALLOW_SEALING);
// becomes
memfd_create(name, MFD_ALLOW_SEALING | MFD_CLOEXEC);
.. title:: clang-tidy - android-cloexec-open
android-cloexec-open
====================
A common source of security bugs is code that opens a file without using the
``O_CLOEXEC`` flag. Without that flag, an opened sensitive file would remain
open across a fork+exec to a lower-privileged SELinux domain, leaking that
sensitive data. Open-like functions including ``open()``, ``openat()``, and
``open64()`` should include ``O_CLOEXEC`` in their flags argument.
Examples:
.. code-block:: c++
open("filename", O_RDWR);
open64("filename", O_RDWR);
openat(0, "filename", O_RDWR);
// becomes
open("filename", O_RDWR | O_CLOEXEC);
open64("filename", O_RDWR | O_CLOEXEC);
openat(0, "filename", O_RDWR | O_CLOEXEC);
.. title:: clang-tidy - android-cloexec-pipe
android-cloexec-pipe
====================
This check detects usage of ``pipe()``. Using ``pipe()`` is not recommended, ``pipe2()`` is the
suggested replacement. The check also adds the O_CLOEXEC flag that marks the file descriptor to
be closed in child processes. Without this flag a sensitive file descriptor can be leaked to a
child process, potentially into a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
pipe(pipefd);
Suggested replacement:
.. code-block:: c++
pipe2(pipefd, O_CLOEXEC);
.. title:: clang-tidy - android-cloexec-pipe2
android-cloexec-pipe2
=====================
This checks ensures that pipe2() is called with the O_CLOEXEC flag. The check also
adds the O_CLOEXEC flag that marks the file descriptor to be closed in child processes.
Without this flag a sensitive file descriptor can be leaked to a child process,
potentially into a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
pipe2(pipefd, O_NONBLOCK);
Suggested replacement:
.. code-block:: c++
pipe2(pipefd, O_NONBLOCK | O_CLOEXEC);
.. title:: clang-tidy - android-cloexec-socket
android-cloexec-socket
======================
``socket()`` should include ``SOCK_CLOEXEC`` in its type argument to avoid the
file descriptor leakage. Without this flag, an opened sensitive file would
remain open across a fork+exec to a lower-privileged SELinux domain.
Examples:
.. code-block:: c++
socket(domain, type, SOCK_STREAM);
// becomes
socket(domain, type, SOCK_STREAM | SOCK_CLOEXEC);
.. title:: clang-tidy - android-comparison-in-temp-failure-retry
android-comparison-in-temp-failure-retry
========================================
Diagnoses comparisons that appear to be incorrectly placed in the argument to
the ``TEMP_FAILURE_RETRY`` macro. Having such a use is incorrect in the vast
majority of cases, and will often silently defeat the purpose of the
``TEMP_FAILURE_RETRY`` macro.
For context, ``TEMP_FAILURE_RETRY`` is `a convenience macro
<https://www.gnu.org/software/libc/manual/html_node/Interrupted-Primitives.html>`_
provided by both glibc and Bionic. Its purpose is to repeatedly run a syscall
until it either succeeds, or fails for reasons other than being interrupted.
Example buggy usage looks like:
.. code-block:: c
char cs[1];
while (TEMP_FAILURE_RETRY(read(STDIN_FILENO, cs, sizeof(cs)) != 0)) {
// Do something with cs.
}
Because TEMP_FAILURE_RETRY will check for whether the result *of the comparison*
is ``-1``, and retry if so.
If you encounter this, the fix is simple: lift the comparison out of the
``TEMP_FAILURE_RETRY`` argument, like so:
.. code-block:: c
char cs[1];
while (TEMP_FAILURE_RETRY(read(STDIN_FILENO, cs, sizeof(cs))) != 0) {
// Do something with cs.
}
Options
-------
.. option:: RetryMacros
A comma-separated list of the names of retry macros to be checked.
.. title:: clang-tidy - boost-use-to-string
boost-use-to-string
===================
This check finds conversion from integer type like ``int`` to ``std::string`` or
``std::wstring`` using ``boost::lexical_cast``, and replace it with calls to
``std::to_string`` and ``std::to_wstring``.
It doesn't replace conversion from floating points despite the ``to_string``
overloads, because it would change the behaviour.
.. code-block:: c++
auto str = boost::lexical_cast<std::string>(42);
auto wstr = boost::lexical_cast<std::wstring>(2137LL);
// Will be changed to
auto str = std::to_string(42);
auto wstr = std::to_wstring(2137LL);
.. title:: clang-tidy - bugprone-argument-comment
bugprone-argument-comment
=========================
Checks that argument comments match parameter names.
The check understands argument comments in the form ``/*parameter_name=*/``
that are placed right before the argument.
.. code-block:: c++
void f(bool foo);
...
f(/*bar=*/true);
// warning: argument name 'bar' in comment does not match parameter name 'foo'
The check tries to detect typos and suggest automated fixes for them.
Options
-------
.. option:: StrictMode
When `false` (default value), the check will ignore leading and trailing
underscores and case when comparing names -- otherwise they are taken into
account.
.. option:: IgnoreSingleArgument
When `true`, the check will ignore the single argument.
.. option:: CommentBoolLiterals
When `true`, the check will add argument comments in the format
``/*ParameterName=*/`` right before the boolean literal argument.
Before:
.. code-block:: c++
void foo(bool TurnKey, bool PressButton);
foo(true, false);
After:
.. code-block:: c++
void foo(bool TurnKey, bool PressButton);
foo(/*TurnKey=*/true, /*PressButton=*/false);
.. option:: CommentIntegerLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the integer literal argument.
Before:
.. code-block:: c++
void foo(int MeaningOfLife);
foo(42);
After:
.. code-block:: c++
void foo(int MeaningOfLife);
foo(/*MeaningOfLife=*/42);
.. option:: CommentFloatLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the float/double literal argument.
Before:
.. code-block:: c++
void foo(float Pi);
foo(3.14159);
After:
.. code-block:: c++
void foo(float Pi);
foo(/*Pi=*/3.14159);
.. option:: CommentStringLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the string literal argument.
Before:
.. code-block:: c++
void foo(const char *String);
void foo(const wchar_t *WideString);
foo("Hello World");
foo(L"Hello World");
After:
.. code-block:: c++
void foo(const char *String);
void foo(const wchar_t *WideString);
foo(/*String=*/"Hello World");
foo(/*WideString=*/L"Hello World");
.. option:: CommentCharacterLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the character literal argument.
Before:
.. code-block:: c++
void foo(char *Character);
foo('A');
After:
.. code-block:: c++
void foo(char *Character);
foo(/*Character=*/'A');
.. option:: CommentUserDefinedLiterals
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the user defined literal argument.
Before:
.. code-block:: c++
void foo(double Distance);
double operator"" _km(long double);
foo(402.0_km);
After:
.. code-block:: c++
void foo(double Distance);
double operator"" _km(long double);
foo(/*Distance=*/402.0_km);
.. option:: CommentNullPtrs
When true, the check will add argument comments in the format
``/*ParameterName=*/`` right before the nullptr literal argument.
Before:
.. code-block:: c++
void foo(A* Value);
foo(nullptr);
After:
.. code-block:: c++
void foo(A* Value);
foo(/*Value=*/nullptr);
.. title:: clang-tidy - bugprone-assert-side-effect
bugprone-assert-side-effect
===========================
Finds ``assert()`` with side effect.
The condition of ``assert()`` is evaluated only in debug builds so a
condition with side effect can cause different behavior in debug / release
builds.
Options
-------
.. option:: AssertMacros
A comma-separated list of the names of assert macros to be checked.
.. option:: CheckFunctionCalls
Whether to treat non-const member and non-member functions as they produce
side effects. Disabled by default because it can increase the number of false
positive warnings.
.. title:: clang-tidy - bugprone-bad-signal-to-kill-thread
bugprone-bad-signal-to-kill-thread
==================================
Finds ``pthread_kill`` function calls when a thread is terminated by
raising ``SIGTERM`` signal and the signal kills the entire process, not
just the individual thread. Use any signal except ``SIGTERM``.
.. code-block: c++
pthread_kill(thread, SIGTERM);
This check corresponds to the CERT C Coding Standard rule
`POS44-C. Do not use signals to terminate threads
<https://wiki.sei.cmu.edu/confluence/display/c/POS44-C.+Do+not+use+signals+to+terminate+threads>`_.
.. title:: clang-tidy - bugprone-bool-pointer-implicit-conversion
bugprone-bool-pointer-implicit-conversion
=========================================
Checks for conditions based on implicit conversion from a ``bool`` pointer to
``bool``.
Example:
.. code-block:: c++
bool *p;
if (p) {
// Never used in a pointer-specific way.
}
.. title:: clang-tidy - bugprone-branch-clone
bugprone-branch-clone
=====================
Checks for repeated branches in ``if/else if/else`` chains, consecutive
repeated branches in ``switch`` statements and identical true and false
branches in conditional operators.
.. code-block:: c++
if (test_value(x)) {
y++;
do_something(x, y);
} else {
y++;
do_something(x, y);
}
In this simple example (which could arise e.g. as a copy-paste error) the
``then`` and ``else`` branches are identical and the code is equivalent the
following shorter and cleaner code:
.. code-block:: c++
test_value(x); // can be omitted unless it has side effects
y++;
do_something(x, y);
If this is the intended behavior, then there is no reason to use a conditional
statement; otherwise the issue can be solved by fixing the branch that is
handled incorrectly.
The check also detects repeated branches in longer ``if/else if/else`` chains
where it would be even harder to notice the problem.
In ``switch`` statements the check only reports repeated branches when they are
consecutive, because it is relatively common that the ``case:`` labels have
some natural ordering and rearranging them would decrease the readability of
the code. For example:
.. code-block:: c++
switch (ch) {
case 'a':
return 10;
case 'A':
return 10;
case 'b':
return 11;
case 'B':
return 11;
default:
return 10;
}
Here the check reports that the ``'a'`` and ``'A'`` branches are identical
(and that the ``'b'`` and ``'B'`` branches are also identical), but does not
report that the ``default:`` branch is also identical to the first two branches.
If this is indeed the correct behavior, then it could be implemented as:
.. code-block:: c++
switch (ch) {
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
default:
return 10;
}
Here the check does not warn for the repeated ``return 10;``, which is good if
we want to preserve that ``'a'`` is before ``'b'`` and ``default:`` is the last
branch.
Finally, the check also examines conditional operators and reports code like:
.. code-block:: c++
return test_value(x) ? x : x;
Unlike if statements, the check does not detect chains of conditional
operators.
Note: This check also reports situations where branches become identical only
after preprocession.
.. title:: clang-tidy - bugprone-copy-constructor-init
bugprone-copy-constructor-init
==============================
Finds copy constructors where the constructor doesn't call
the copy constructor of the base class.
.. code-block:: c++
class Copyable {
public:
Copyable() = default;
Copyable(const Copyable &) = default;
};
class X2 : public Copyable {
X2(const X2 &other) {} // Copyable(other) is missing
};
Also finds copy constructors where the constructor of
the base class don't have parameter.
.. code-block:: c++
class X4 : public Copyable {
X4(const X4 &other) : Copyable() {} // other is missing
};
The check also suggests a fix-its in some cases.
.. title:: clang-tidy - bugprone-dangling-handle
bugprone-dangling-handle
========================
Detect dangling references in value handles like ``std::string_view``.
These dangling references can be a result of constructing handles from temporary
values, where the temporary is destroyed soon after the handle is created.
Examples:
.. code-block:: c++
string_view View = string(); // View will dangle.
string A;
View = A + "A"; // still dangle.
vector<string_view> V;
V.push_back(string()); // V[0] is dangling.
V.resize(3, string()); // V[1] and V[2] will also dangle.
string_view f() {
// All these return values will dangle.
return string();
string S;
return S;
char Array[10]{};
return Array;
}
Options
-------
.. option:: HandleClasses
A semicolon-separated list of class names that should be treated as handles.
By default only ``std::basic_string_view`` and
``std::experimental::basic_string_view`` are considered.
.. title:: clang-tidy - bugprone-dynamic-static-initializers
bugprone-dynamic-static-initializers
====================================
Finds instances of static variables that are dynamically initialized
in header files.
This can pose problems in certain multithreaded contexts. For example,
when disabling compiler generated synchronization instructions for
static variables initialized at runtime (e.g. by ``-fno-threadsafe-statics``), even if a particular project
takes the necessary precautions to prevent race conditions during
initialization by providing their own synchronization, header files included from other projects may
not. Therefore, such a check is helpful for ensuring that disabling
compiler generated synchronization for static variable initialization will not cause
problems.
Consider the following code:
.. code-block:: c
int foo() {
static int k = bar();
return k;
}
When synchronization of static initialization is disabled, if two threads both call `foo` for the first time, there is the possibility that `k` will be double initialized, creating a race condition.
.. title:: clang-tidy - bugprone-exception-escape
bugprone-exception-escape
=========================
Finds functions which may throw an exception directly or indirectly, but they
should not. The functions which should not throw exceptions are the following:
* Destructors
* Move constructors
* Move assignment operators
* The ``main()`` functions
* ``swap()`` functions
* Functions marked with ``throw()`` or ``noexcept``
* Other functions given as option
A destructor throwing an exception may result in undefined behavior, resource
leaks or unexpected termination of the program. Throwing move constructor or
move assignment also may result in undefined behavior or resource leak. The
``swap()`` operations expected to be non throwing most of the cases and they
are always possible to implement in a non throwing way. Non throwing ``swap()``
operations are also used to create move operations. A throwing ``main()``
function also results in unexpected termination.
WARNING! This check may be expensive on large source files.
Options
-------
.. option:: FunctionsThatShouldNotThrow
Comma separated list containing function names which should not throw. An
example value for this parameter can be ``WinMain`` which adds function
``WinMain()`` in the Windows API to the list of the functions which should
not throw. Default value is an empty string.
.. option:: IgnoredExceptions
Comma separated list containing type names which are not counted as thrown
exceptions in the check. Default value is an empty string.
.. title:: clang-tidy - bugprone-fold-init-type
bugprone-fold-init-type
=======================
The check flags type mismatches in
`folds <https://en.wikipedia.org/wiki/Fold_(higher-order_function)>`_
like ``std::accumulate`` that might result in loss of precision.
``std::accumulate`` folds an input range into an initial value using the type of
the latter, with ``operator+`` by default. This can cause loss of precision
through:
- Truncation: The following code uses a floating point range and an int
initial value, so trucation will happen at every application of ``operator+``
and the result will be `0`, which might not be what the user expected.
.. code-block:: c++
auto a = {0.5f, 0.5f, 0.5f, 0.5f};
return std::accumulate(std::begin(a), std::end(a), 0);
- Overflow: The following code also returns `0`.
.. code-block:: c++
auto a = {65536LL * 65536 * 65536};
return std::accumulate(std::begin(a), std::end(a), 0);
.. title:: clang-tidy - bugprone-forward-declaration-namespace
bugprone-forward-declaration-namespace
======================================
Checks if an unused forward declaration is in a wrong namespace.
The check inspects all unused forward declarations and checks if there is any
declaration/definition with the same name existing, which could indicate that
the forward declaration is in a potentially wrong namespace.
.. code-block:: c++
namespace na { struct A; }
namespace nb { struct A {}; }
nb::A a;
// warning : no definition found for 'A', but a definition with the same name
// 'A' found in another namespace 'nb::'
This check can only generate warnings, but it can't suggest a fix at this point.
.. title:: clang-tidy - bugprone-forwarding-reference-overload
bugprone-forwarding-reference-overload
======================================
The check looks for perfect forwarding constructors that can hide copy or move
constructors. If a non const lvalue reference is passed to the constructor, the
forwarding reference parameter will be a better match than the const reference
parameter of the copy constructor, so the perfect forwarding constructor will be
called, which can be confusing.
For detailed description of this issue see: Scott Meyers, Effective Modern C++,
Item 26.
Consider the following example:
.. code-block:: c++
class Person {
public:
// C1: perfect forwarding ctor
template<typename T>
explicit Person(T&& n) {}
// C2: perfect forwarding ctor with parameter default value
template<typename T>
explicit Person(T&& n, int x = 1) {}
// C3: perfect forwarding ctor guarded with enable_if
template<typename T, typename X = enable_if_t<is_special<T>,void>>
explicit Person(T&& n) {}
// (possibly compiler generated) copy ctor
Person(const Person& rhs);
};
The check warns for constructors C1 and C2, because those can hide copy and move
constructors. We suppress warnings if the copy and the move constructors are both
disabled (deleted or private), because there is nothing the perfect forwarding
constructor could hide in this case. We also suppress warnings for constructors
like C3 that are guarded with an ``enable_if``, assuming the programmer was aware of
the possible hiding.
Background
----------
For deciding whether a constructor is guarded with enable_if, we consider the
default values of the type parameters and the types of the constructor
parameters. If any part of these types is ``std::enable_if`` or ``std::enable_if_t``,
we assume the constructor is guarded.
.. title:: clang-tidy - bugprone-implicit-widening-of-multiplication-result
bugprone-implicit-widening-of-multiplication-result
===================================================
The check diagnoses instances where a result of a multiplication is implicitly
widened, and suggests (with fix-it) to either silence the code by making
widening explicit, or to perform the multiplication in a wider type,
to avoid the widening afterwards.
This is mainly useful when operating on a very large buffers.
For example, consider:
.. code-block:: c++
void zeroinit(char* base, unsigned width, unsigned height) {
for(unsigned row = 0; row != height; ++row) {
for(unsigned col = 0; col != width; ++col) {
char* ptr = base + row * width + col;
*ptr = 0;
}
}
}
This is fine in general, but iff ``width * height`` overflows,
you end up wrapping back to the beginning of ``base``
instead of processing the entire requested buffer.
Indeed, this only matters for pretty large buffers (4GB+),
but that can happen very easily for example in image processing,
where for that to happen you "only" need a ~269MPix image.
Options
-------
.. option:: UseCXXStaticCastsInCppSources
When suggesting fix-its for C++ code, should C++-style ``static_cast<>()``'s
be suggested, or C-style casts. Defaults to ``true``.
.. option:: UseCXXHeadersInCppSources
When suggesting to include the appropriate header in C++ code,
should ``<cstddef>`` header be suggested, or ``<stddef.h>``.
Defaults to ``true``.
Examples:
.. code-block:: c++
long mul(int a, int b) {
return a * b; // warning: performing an implicit widening conversion to type 'long' of a multiplication performed in type 'int'
}
char* ptr_add(char *base, int a, int b) {
return base + a * b; // warning: result of multiplication in type 'int' is used as a pointer offset after an implicit widening conversion to type 'ssize_t'
}
char ptr_subscript(char *base, int a, int b) {
return base[a * b]; // warning: result of multiplication in type 'int' is used as a pointer offset after an implicit widening conversion to type 'ssize_t'
}
.. title:: clang-tidy - bugprone-inaccurate-erase
bugprone-inaccurate-erase
=========================
Checks for inaccurate use of the ``erase()`` method.
Algorithms like ``remove()`` do not actually remove any element from the
container but return an iterator to the first redundant element at the end
of the container. These redundant elements must be removed using the
``erase()`` method. This check warns when not all of the elements will be
removed due to using an inappropriate overload.
For example, the following code erases only one element:
.. code-block:: c++
std::vector<int> xs;
...
xs.erase(std::remove(xs.begin(), xs.end(), 10));
Call the two-argument overload of ``erase()`` to remove the subrange:
.. code-block:: c++
std::vector<int> xs;
...
xs.erase(std::remove(xs.begin(), xs.end(), 10), xs.end());
.. title:: clang-tidy - bugprone-incorrect-roundings
bugprone-incorrect-roundings
============================
Checks the usage of patterns known to produce incorrect rounding.
Programmers often use::
(int)(double_expression + 0.5)
to round the double expression to an integer. The problem with this:
1. It is unnecessarily slow.
2. It is incorrect. The number 0.499999975 (smallest representable float
number below 0.5) rounds to 1.0. Even worse behavior for negative
numbers where both -0.5f and -1.4f both round to 0.0.
.. title:: clang-tidy - bugprone-infinite-loop
bugprone-infinite-loop
======================
Finds obvious infinite loops (loops where the condition variable is not changed
at all).
Finding infinite loops is well-known to be impossible (halting problem).
However, it is possible to detect some obvious infinite loops, for example, if
the loop condition is not changed. This check detects such loops. A loop is
considered infinite if it does not have any loop exit statement (``break``,
``continue``, ``goto``, ``return``, ``throw`` or a call to a function called as
``[[noreturn]]``) and all of the following conditions hold for every variable in
the condition:
- It is a local variable.
- It has no reference or pointer aliases.
- It is not a structure or class member.
Furthermore, the condition must not contain a function call to consider the loop
infinite since functions may return different values for different calls.
For example, the following loop is considered infinite `i` is not changed in
the body:
.. code-block:: c++
int i = 0, j = 0;
while (i < 10) {
++j;
}
.. title:: clang-tidy - bugprone-integer-division
bugprone-integer-division
=========================
Finds cases where integer division in a floating point context is likely to
cause unintended loss of precision.
No reports are made if divisions are part of the following expressions:
- operands of operators expecting integral or bool types,
- call expressions of integral or bool types, and
- explicit cast expressions to integral or bool types,
as these are interpreted as signs of deliberateness from the programmer.
Examples:
.. code-block:: c++
float floatFunc(float);
int intFunc(int);
double d;
int i = 42;
// Warn, floating-point values expected.
d = 32 * 8 / (2 + i);
d = 8 * floatFunc(1 + 7 / 2);
d = i / (1 << 4);
// OK, no integer division.
d = 32 * 8.0 / (2 + i);
d = 8 * floatFunc(1 + 7.0 / 2);
d = (double)i / (1 << 4);
// OK, there are signs of deliberateness.
d = 1 << (i / 2);
d = 9 + intFunc(6 * i / 32);
d = (int)(i / 32) - 8;
.. title:: clang-tidy - bugprone-lambda-function-name
bugprone-lambda-function-name
=============================
Checks for attempts to get the name of a function from within a lambda
expression. The name of a lambda is always something like ``operator()``, which
is almost never what was intended.
Example:
.. code-block:: c++
void FancyFunction() {
[] { printf("Called from %s\n", __func__); }();
[] { printf("Now called from %s\n", __FUNCTION__); }();
}
Output::
Called from operator()
Now called from operator()
Likely intended output::
Called from FancyFunction
Now called from FancyFunction
.. title:: clang-tidy - bugprone-macro-parentheses
bugprone-macro-parentheses
==========================
Finds macros that can have unexpected behaviour due to missing parentheses.
Macros are expanded by the preprocessor as-is. As a result, there can be
unexpected behaviour; operators may be evaluated in unexpected order and
unary operators may become binary operators, etc.
When the replacement list has an expression, it is recommended to surround
it with parentheses. This ensures that the macro result is evaluated
completely before it is used.
It is also recommended to surround macro arguments in the replacement list
with parentheses. This ensures that the argument value is calculated
properly.
.. title:: clang-tidy - bugprone-macro-repeated-side-effects
bugprone-macro-repeated-side-effects
====================================
Checks for repeated argument with side effects in macros.
.. title:: clang-tidy - bugprone-misplaced-operator-in-strlen-in-alloc
bugprone-misplaced-operator-in-strlen-in-alloc
==============================================
Finds cases where ``1`` is added to the string in the argument to ``strlen()``,
``strnlen()``, ``strnlen_s()``, ``wcslen()``, ``wcsnlen()``, and ``wcsnlen_s()``
instead of the result and the value is used as an argument to a memory
allocation function (``malloc()``, ``calloc()``, ``realloc()``, ``alloca()``) or
the ``new[]`` operator in `C++`. The check detects error cases even if one of
these functions (except the ``new[]`` operator) is called by a constant function
pointer. Cases where ``1`` is added both to the parameter and the result of the
``strlen()``-like function are ignored, as are cases where the whole addition is
surrounded by extra parentheses.
`C` example code:
.. code-block:: c
void bad_malloc(char *str) {
char *c = (char*) malloc(strlen(str + 1));
}
The suggested fix is to add ``1`` to the return value of ``strlen()`` and not
to its argument. In the example above the fix would be
.. code-block:: c
char *c = (char*) malloc(strlen(str) + 1);
`C++` example code:
.. code-block:: c++
void bad_new(char *str) {
char *c = new char[strlen(str + 1)];
}
As in the `C` code with the ``malloc()`` function, the suggested fix is to
add ``1`` to the return value of ``strlen()`` and not to its argument. In the
example above the fix would be
.. code-block:: c++
char *c = new char[strlen(str) + 1];
Example for silencing the diagnostic:
.. code-block:: c
void bad_malloc(char *str) {
char *c = (char*) malloc(strlen((str + 1)));
}
.. title:: clang-tidy - bugprone-misplaced-pointer-arithmetic-in-alloc
bugprone-misplaced-pointer-arithmetic-in-alloc
===============================================
Finds cases where an integer expression is added to or subtracted from the
result of a memory allocation function (``malloc()``, ``calloc()``,
``realloc()``, ``alloca()``) instead of its argument. The check detects error
cases even if one of these functions is called by a constant function pointer.
Example code:
.. code-block:: c
void bad_malloc(int n) {
char *p = (char*) malloc(n) + 10;
}
The suggested fix is to add the integer expression to the argument of
``malloc`` and not to its result. In the example above the fix would be
.. code-block:: c
char *p = (char*) malloc(n + 10);
.. title:: clang-tidy - bugprone-misplaced-widening-cast
bugprone-misplaced-widening-cast
================================
This check will warn when there is a cast of a calculation result to a bigger
type. If the intention of the cast is to avoid loss of precision then the cast
is misplaced, and there can be loss of precision. Otherwise the cast is
ineffective.
Example code:
.. code-block:: c++
long f(int x) {
return (long)(x * 1000);
}
The result ``x * 1000`` is first calculated using ``int`` precision. If the
result exceeds ``int`` precision there is loss of precision. Then the result is
casted to ``long``.
If there is no loss of precision then the cast can be removed or you can
explicitly cast to ``int`` instead.
If you want to avoid loss of precision then put the cast in a proper location,
for instance:
.. code-block:: c++
long f(int x) {
return (long)x * 1000;
}
Implicit casts
--------------
Forgetting to place the cast at all is at least as dangerous and at least as
common as misplacing it. If :option:`CheckImplicitCasts` is enabled the check
also detects these cases, for instance:
.. code-block:: c++
long f(int x) {
return x * 1000;
}
Floating point
--------------
Currently warnings are only written for integer conversion. No warning is
written for this code:
.. code-block:: c++
double f(float x) {
return (double)(x * 10.0f);
}
Options
-------
.. option:: CheckImplicitCasts
If `true`, enables detection of implicit casts. Default is `false`.
.. title:: clang-tidy - bugprone-move-forwarding-reference
bugprone-move-forwarding-reference
==================================
Warns if ``std::move`` is called on a forwarding reference, for example:
.. code-block:: c++
template <typename T>
void foo(T&& t) {
bar(std::move(t));
}
`Forwarding references
<http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4164.pdf>`_ should
typically be passed to ``std::forward`` instead of ``std::move``, and this is
the fix that will be suggested.
(A forwarding reference is an rvalue reference of a type that is a deduced
function template argument.)
In this example, the suggested fix would be
.. code-block:: c++
bar(std::forward<T>(t));
Background
----------
Code like the example above is sometimes written with the expectation that
``T&&`` will always end up being an rvalue reference, no matter what type is
deduced for ``T``, and that it is therefore not possible to pass an lvalue to
``foo()``. However, this is not true. Consider this example:
.. code-block:: c++
std::string s = "Hello, world";
foo(s);
This code compiles and, after the call to ``foo()``, ``s`` is left in an
indeterminate state because it has been moved from. This may be surprising to
the caller of ``foo()`` because no ``std::move`` was used when calling
``foo()``.
The reason for this behavior lies in the special rule for template argument
deduction on function templates like ``foo()`` -- i.e. on function templates
that take an rvalue reference argument of a type that is a deduced function
template argument. (See section [temp.deduct.call]/3 in the C++11 standard.)
If ``foo()`` is called on an lvalue (as in the example above), then ``T`` is
deduced to be an lvalue reference. In the example, ``T`` is deduced to be
``std::string &``. The type of the argument ``t`` therefore becomes
``std::string& &&``; by the reference collapsing rules, this collapses to
``std::string&``.
This means that the ``foo(s)`` call passes ``s`` as an lvalue reference, and
``foo()`` ends up moving ``s`` and thereby placing it into an indeterminate
state.
.. title:: clang-tidy - bugprone-multiple-statement-macro
bugprone-multiple-statement-macro
=================================
Detect multiple statement macros that are used in unbraced conditionals. Only
the first statement of the macro will be inside the conditional and the other
ones will be executed unconditionally.
Example:
.. code-block:: c++
#define INCREMENT_TWO(x, y) (x)++; (y)++
if (do_increment)
INCREMENT_TWO(a, b); // (b)++ will be executed unconditionally.
.. title:: clang-tidy - bugprone-no-escape
bugprone-no-escape
==================
Finds pointers with the ``noescape`` attribute that are captured by an
asynchronously-executed block. The block arguments in ``dispatch_async()`` and
``dispatch_after()`` are guaranteed to escape, so it is an error if a pointer with the
``noescape`` attribute is captured by one of these blocks.
The following is an example of an invalid use of the ``noescape`` attribute.
.. code-block:: objc
void foo(__attribute__((noescape)) int *p) {
dispatch_async(queue, ^{
*p = 123;
});
});
.. title:: clang-tidy - bugprone-not-null-terminated-result
bugprone-not-null-terminated-result
===================================
Finds function calls where it is possible to cause a not null-terminated result.
Usually the proper length of a string is ``strlen(src) + 1`` or equal length of
this expression, because the null terminator needs an extra space. Without the
null terminator it can result in undefined behaviour when the string is read.
The following and their respective ``wchar_t`` based functions are checked:
``memcpy``, ``memcpy_s``, ``memchr``, ``memmove``, ``memmove_s``,
``strerror_s``, ``strncmp``, ``strxfrm``
The following is a real-world example where the programmer forgot to increase
the passed third argument, which is ``size_t length``. That is why the length
of the allocated memory is not enough to hold the null terminator.
.. code-block:: c
static char *stringCpy(const std::string &str) {
char *result = reinterpret_cast<char *>(malloc(str.size()));
memcpy(result, str.data(), str.size());
return result;
}
In addition to issuing warnings, fix-it rewrites all the necessary code. It also
tries to adjust the capacity of the destination array:
.. code-block:: c
static char *stringCpy(const std::string &str) {
char *result = reinterpret_cast<char *>(malloc(str.size() + 1));
strcpy(result, str.data());
return result;
}
Note: It cannot guarantee to rewrite every of the path-sensitive memory
allocations.
.. _MemcpyTransformation:
Transformation rules of 'memcpy()'
----------------------------------
It is possible to rewrite the ``memcpy()`` and ``memcpy_s()`` calls as the
following four functions: ``strcpy()``, ``strncpy()``, ``strcpy_s()``,
``strncpy_s()``, where the latter two are the safer versions of the former two.
It rewrites the ``wchar_t`` based memory handler functions respectively.
Rewrite based on the destination array
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- If copy to the destination array cannot overflow [1] the new function should
be the older copy function (ending with ``cpy``), because it is more
efficient than the safe version.
- If copy to the destination array can overflow [1] and
:option:`WantToUseSafeFunctions` is set to `true` and it is possible to
obtain the capacity of the destination array then the new function could be
the safe version (ending with ``cpy_s``).
- If the new function is could be safe version and C++ files are analysed and
the destination array is plain ``char``/``wchar_t`` without ``un/signed`` then
the length of the destination array can be omitted.
- If the new function is could be safe version and the destination array is
``un/signed`` it needs to be casted to plain ``char *``/``wchar_t *``.
[1] It is possible to overflow:
- If the capacity of the destination array is unknown.
- If the given length is equal to the destination array's capacity.
Rewrite based on the length of the source string
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- If the given length is ``strlen(source)`` or equal length of this expression
then the new function should be the older copy function (ending with ``cpy``),
as it is more efficient than the safe version (ending with ``cpy_s``).
- Otherwise we assume that the programmer wanted to copy 'N' characters, so the
new function is ``ncpy``-like which copies 'N' characters.
Transformations with 'strlen()' or equal length of this expression
------------------------------------------------------------------
It transforms the ``wchar_t`` based memory and string handler functions
respectively (where only ``strerror_s`` does not have ``wchar_t`` based alias).
Memory handler functions
^^^^^^^^^^^^^^^^^^^^^^^^
``memcpy``
Please visit the
:ref:`Transformation rules of 'memcpy()'<MemcpyTransformation>` section.
``memchr``
Usually there is a C-style cast and it is needed to be removed, because the
new function ``strchr``'s return type is correct. The given length is going
to be removed.
``memmove``
If safe functions are available the new function is ``memmove_s``, which has
a new second argument which is the length of the destination array, it is
adjusted, and the length of the source string is incremented by one.
If safe functions are not available the given length is incremented by one.
``memmove_s``
The given length is incremented by one.
String handler functions
^^^^^^^^^^^^^^^^^^^^^^^^
``strerror_s``
The given length is incremented by one.
``strncmp``
If the third argument is the first or the second argument's ``length + 1``
it has to be truncated without the ``+ 1`` operation.
``strxfrm``
The given length is incremented by one.
Options
-------
.. option:: WantToUseSafeFunctions
The value `true` specifies that the target environment is considered to
implement '_s' suffixed memory and string handler functions which are safer
than older versions (e.g. 'memcpy_s()'). The default value is `true`.
.. title:: clang-tidy - bugprone-parent-virtual-call
bugprone-parent-virtual-call
============================
Detects and fixes calls to grand-...parent virtual methods instead of calls
to overridden parent's virtual methods.
.. code-block:: c++
struct A {
int virtual foo() {...}
};
struct B: public A {
int foo() override {...}
};
struct C: public B {
int foo() override { A::foo(); }
// ^^^^^^^^
// warning: qualified name A::foo refers to a member overridden in subclass; did you mean 'B'? [bugprone-parent-virtual-call]
};
.. title:: clang-tidy - bugprone-posix-return
bugprone-posix-return
=====================
Checks if any calls to ``pthread_*`` or ``posix_*`` functions
(except ``posix_openpt``) expect negative return values. These functions return
either ``0`` on success or an ``errno`` on failure, which is positive only.
Example buggy usage looks like:
.. code-block:: c
if (posix_fadvise(...) < 0) {
This will never happen as the return value is always non-negative. A simple fix could be:
.. code-block:: c
if (posix_fadvise(...) > 0) {
.. title:: clang-tidy - bugprone-redundant-branch-condition
bugprone-redundant-branch-condition
===================================
Finds condition variables in nested ``if`` statements that were also checked in
the outer ``if`` statement and were not changed.
Simple example:
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
if (onFire)
scream();
}
Here `onFire` is checked both in the outer ``if`` and the inner ``if`` statement
without a possible change between the two checks. The check warns for this code
and suggests removal of the second checking of variable `onFire`.
The checker also detects redundant condition checks if the condition variable
is an operand of a logical "and" (``&&``) or a logical "or" (``||``) operator:
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
if (onFire && peopleInTheBuilding > 0)
scream();
}
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
if (onFire || isCollapsing())
scream();
}
In the first case (logical "and") the suggested fix is to remove the redundant
condition variable and keep the other side of the ``&&``. In the second case
(logical "or") the whole ``if`` is removed similarily to the simple case on the
top.
The condition of the outer ``if`` statement may also be a logical "and" (``&&``)
expression:
.. code-block:: c
bool onFire = isBurning();
if (onFire && fireFighters < 10) {
if (someOtherCondition()) {
if (onFire)
scream();
}
}
The error is also detected if both the outer statement is a logical "and"
(``&&``) and the inner statement is a logical "and" (``&&``) or "or" (``||``).
The inner ``if`` statement does not have to be a direct descendant of the outer
one.
No error is detected if the condition variable may have been changed between the
two checks:
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
tryToExtinguish(onFire);
if (onFire && peopleInTheBuilding > 0)
scream();
}
Every possible change is considered, thus if the condition variable is not
a local variable of the function, it is a volatile or it has an alias (pointer
or reference) then no warning is issued.
Known limitations
^^^^^^^^^^^^^^^^^
The ``else`` branch is not checked currently for negated condition variable:
.. code-block:: c
bool onFire = isBurning();
if (onFire) {
scream();
} else {
if (!onFire) {
continueWork();
}
}
The checker currently only detects redundant checking of single condition
variables. More complex expressions are not checked:
.. code-block:: c
if (peopleInTheBuilding == 1) {
if (peopleInTheBuilding == 1) {
doSomething();
}
}
.. title:: clang-tidy - bugprone-reserved-identifier
bugprone-reserved-identifier
============================
`cert-dcl37-c` and `cert-dcl51-cpp` redirect here as an alias for this check.
Checks for usages of identifiers reserved for use by the implementation.
The C and C++ standards both reserve the following names for such use:
- identifiers that begin with an underscore followed by an uppercase letter;
- identifiers in the global namespace that begin with an underscore.
The C standard additionally reserves names beginning with a double underscore,
while the C++ standard strengthens this to reserve names with a double
underscore occurring anywhere.
Violating the naming rules above results in undefined behavior.
.. code-block:: c++
namespace NS {
void __f(); // name is not allowed in user code
using _Int = int; // same with this
#define cool__macro // also this
}
int _g(); // disallowed in global namespace only
The check can also be inverted, i.e. it can be configured to flag any
identifier that is _not_ a reserved identifier. This mode is for use by e.g.
standard library implementors, to ensure they don't infringe on the user
namespace.
This check does not (yet) check for other reserved names, e.g. macro names
identical to language keywords, and names specifically reserved by language
standards, e.g. C++ 'zombie names' and C future library directions.
This check corresponds to CERT C Coding Standard rule `DCL37-C. Do not declare
or define a reserved identifier
<https://wiki.sei.cmu.edu/confluence/display/c/DCL37-C.+Do+not+declare+or+define+a+reserved+identifier>`_
as well as its C++ counterpart, `DCL51-CPP. Do not declare or define a reserved
identifier
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/DCL51-CPP.+Do+not+declare+or+define+a+reserved+identifier>`_.
Options
-------
.. option:: Invert
If `true`, inverts the check, i.e. flags names that are not reserved.
Default is `false`.
.. option:: AllowedIdentifiers
Semicolon-separated list of names that the check ignores. Default is an
empty list.
.. title:: clang-tidy - bugprone-signal-handler
bugprone-signal-handler
=======================
Finds functions registered as signal handlers that call non asynchronous-safe
functions. Any function that cannot be determined to be an asynchronous-safe
function call is assumed to be non-asynchronous-safe by the checker,
including user functions for which only the declaration is visible.
User function calls with visible definition are checked recursively.
The check handles only C code. Only the function names are considered and the
fact that the function is a system-call, but no other restrictions on the
arguments passed to the functions (the ``signal`` call is allowed without
restrictions).
This check corresponds to the CERT C Coding Standard rule
`SIG30-C. Call only asynchronous-safe functions within signal handlers
<https://www.securecoding.cert.org/confluence/display/c/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal+handlers>`_
and has an alias name ``cert-sig30-c``.
.. option:: AsyncSafeFunctionSet
Selects wich set of functions is considered as asynchronous-safe
(and therefore allowed in signal handlers). Value ``minimal`` selects
a minimal set that is defined in the CERT SIG30-C rule and includes functions
``abort()``, ``_Exit()``, ``quick_exit()`` and ``signal()``. Value ``POSIX``
selects a larger set of functions that is listed in POSIX.1-2017 (see `this
link
<https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_03>`_
for more information).
The function ``quick_exit`` is not included in the shown list. It is
assumable that the reason is that the list was not updated for C11.
The checker includes ``quick_exit`` in the set of safe functions.
Functions registered as exit handlers are not checked.
Default is ``POSIX``.
.. title:: clang-tidy - bugprone-signed-char-misuse
bugprone-signed-char-misuse
===========================
`cert-str34-c` redirects here as an alias for this check. For the CERT alias,
the `DiagnoseSignedUnsignedCharComparisons` option is set to `false`.
Finds those ``signed char`` -> integer conversions which might indicate a
programming error. The basic problem with the ``signed char``, that it might
store the non-ASCII characters as negative values. This behavior can cause a
misunderstanding of the written code both when an explicit and when an
implicit conversion happens.
When the code contains an explicit ``signed char`` -> integer conversion, the
human programmer probably expects that the converted value matches with the
character code (a value from [0..255]), however, the actual value is in
[-128..127] interval. To avoid this kind of misinterpretation, the desired way
of converting from a ``signed char`` to an integer value is converting to
``unsigned char`` first, which stores all the characters in the positive [0..255]
interval which matches the known character codes.
In case of implicit conversion, the programmer might not actually be aware
that a conversion happened and char value is used as an integer. There are
some use cases when this unawareness might lead to a functionally imperfect code.
For example, checking the equality of a ``signed char`` and an ``unsigned char``
variable is something we should avoid in C++ code. During this comparison,
the two variables are converted to integers which have different value ranges.
For ``signed char``, the non-ASCII characters are stored as a value in [-128..-1]
interval, while the same characters are stored in the [128..255] interval for
an ``unsigned char``.
It depends on the actual platform whether plain ``char`` is handled as ``signed char``
by default and so it is caught by this check or not. To change the default behavior
you can use ``-funsigned-char`` and ``-fsigned-char`` compilation options.
Currently, this check warns in the following cases:
- ``signed char`` is assigned to an integer variable
- ``signed char`` and ``unsigned char`` are compared with equality/inequality operator
- ``signed char`` is converted to an integer in the array subscript
See also:
`STR34-C. Cast characters to unsigned char before converting to larger integer sizes
<https://wiki.sei.cmu.edu/confluence/display/c/STR34-C.+Cast+characters+to+unsigned+char+before+converting+to+larger+integer+sizes>`_
A good example from the CERT description when a ``char`` variable is used to
read from a file that might contain non-ASCII characters. The problem comes
up when the code uses the ``-1`` integer value as EOF, while the 255 character
code is also stored as ``-1`` in two's complement form of char type.
See a simple example of this bellow. This code stops not only when it reaches
the end of the file, but also when it gets a character with the 255 code.
.. code-block:: c++
#define EOF (-1)
int read(void) {
char CChar;
int IChar = EOF;
if (readChar(CChar)) {
IChar = CChar;
}
return IChar;
}
A proper way to fix the code above is converting the ``char`` variable to
an ``unsigned char`` value first.
.. code-block:: c++
#define EOF (-1)
int read(void) {
char CChar;
int IChar = EOF;
if (readChar(CChar)) {
IChar = static_cast<unsigned char>(CChar);
}
return IChar;
}
Another use case is checking the equality of two ``char`` variables with
different signedness. Inside the non-ASCII value range this comparison between
a ``signed char`` and an ``unsigned char`` always returns ``false``.
.. code-block:: c++
bool compare(signed char SChar, unsigned char USChar) {
if (SChar == USChar)
return true;
return false;
}
The easiest way to fix this kind of comparison is casting one of the arguments,
so both arguments will have the same type.
.. code-block:: c++
bool compare(signed char SChar, unsigned char USChar) {
if (static_cast<unsigned char>(SChar) == USChar)
return true;
return false;
}
.. option:: CharTypdefsToIgnore
A semicolon-separated list of typedef names. In this list, we can list
typedefs for ``char`` or ``signed char``, which will be ignored by the
check. This is useful when a typedef introduces an integer alias like
``sal_Int8`` or ``int8_t``. In this case, human misinterpretation is not
an issue.
.. option:: DiagnoseSignedUnsignedCharComparisons
When `true`, the check will warn on ``signed char``/``unsigned char`` comparisons,
otherwise these comparisons are ignored. By default, this option is set to `true`.
.. title:: clang-tidy - bugprone-sizeof-container
bugprone-sizeof-container
=========================
The check finds usages of ``sizeof`` on expressions of STL container types. Most
likely the user wanted to use ``.size()`` instead.
All class/struct types declared in namespace ``std::`` having a const ``size()``
method are considered containers, with the exception of ``std::bitset`` and
``std::array``.
Examples:
.. code-block:: c++
std::string s;
int a = 47 + sizeof(s); // warning: sizeof() doesn't return the size of the container. Did you mean .size()?
int b = sizeof(std::string); // no warning, probably intended.
std::string array_of_strings[10];
int c = sizeof(array_of_strings) / sizeof(array_of_strings[0]); // no warning, definitely intended.
std::array<int, 3> std_array;
int d = sizeof(std_array); // no warning, probably intended.
.. title:: clang-tidy - bugprone-sizeof-expression
bugprone-sizeof-expression
==========================
The check finds usages of ``sizeof`` expressions which are most likely errors.
The ``sizeof`` operator yields the size (in bytes) of its operand, which may be
an expression or the parenthesized name of a type. Misuse of this operator may
be leading to errors and possible software vulnerabilities.
Suspicious usage of 'sizeof(K)'
-------------------------------
A common mistake is to query the ``sizeof`` of an integer literal. This is
equivalent to query the size of its type (probably ``int``). The intent of the
programmer was probably to simply get the integer and not its size.
.. code-block:: c++
#define BUFLEN 42
char buf[BUFLEN];
memset(buf, 0, sizeof(BUFLEN)); // sizeof(42) ==> sizeof(int)
Suspicious usage of 'sizeof(expr)'
----------------------------------
In cases, where there is an enum or integer to represent a type, a common
mistake is to query the ``sizeof`` on the integer or enum that represents the
type that should be used by ``sizeof``. This results in the size of the integer
and not of the type the integer represents:
.. code-block:: c++
enum data_type {
FLOAT_TYPE,
DOUBLE_TYPE
};
struct data {
data_type type;
void* buffer;
data_type get_type() {
return type;
}
};
void f(data d, int numElements) {
// should be sizeof(float) or sizeof(double), depending on d.get_type()
int numBytes = numElements * sizeof(d.get_type());
...
}
Suspicious usage of 'sizeof(this)'
----------------------------------
The ``this`` keyword is evaluated to a pointer to an object of a given type.
The expression ``sizeof(this)`` is returning the size of a pointer. The
programmer most likely wanted the size of the object and not the size of the
pointer.
.. code-block:: c++
class Point {
[...]
size_t size() { return sizeof(this); } // should probably be sizeof(*this)
[...]
};
Suspicious usage of 'sizeof(char*)'
-----------------------------------
There is a subtle difference between declaring a string literal with
``char* A = ""`` and ``char A[] = ""``. The first case has the type ``char*``
instead of the aggregate type ``char[]``. Using ``sizeof`` on an object declared
with ``char*`` type is returning the size of a pointer instead of the number of
characters (bytes) in the string literal.
.. code-block:: c++
const char* kMessage = "Hello World!"; // const char kMessage[] = "...";
void getMessage(char* buf) {
memcpy(buf, kMessage, sizeof(kMessage)); // sizeof(char*)
}
Suspicious usage of 'sizeof(A*)'
--------------------------------
A common mistake is to compute the size of a pointer instead of its pointee.
These cases may occur because of explicit cast or implicit conversion.
.. code-block:: c++
int A[10];
memset(A, 0, sizeof(A + 0));
struct Point point;
memset(point, 0, sizeof(&point));
Suspicious usage of 'sizeof(...)/sizeof(...)'
---------------------------------------------
Dividing ``sizeof`` expressions is typically used to retrieve the number of
elements of an aggregate. This check warns on incompatible or suspicious cases.
In the following example, the entity has 10-bytes and is incompatible with the
type ``int`` which has 4 bytes.
.. code-block:: c++
char buf[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // sizeof(buf) => 10
void getMessage(char* dst) {
memcpy(dst, buf, sizeof(buf) / sizeof(int)); // sizeof(int) => 4 [incompatible sizes]
}
In the following example, the expression ``sizeof(Values)`` is returning the
size of ``char*``. One can easily be fooled by its declaration, but in parameter
declaration the size '10' is ignored and the function is receiving a ``char*``.
.. code-block:: c++
char OrderedValues[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
return CompareArray(char Values[10]) {
return memcmp(OrderedValues, Values, sizeof(Values)) == 0; // sizeof(Values) ==> sizeof(char*) [implicit cast to char*]
}
Suspicious 'sizeof' by 'sizeof' expression
------------------------------------------
Multiplying ``sizeof`` expressions typically makes no sense and is probably a
logic error. In the following example, the programmer used ``*`` instead of
``/``.
.. code-block:: c++
const char kMessage[] = "Hello World!";
void getMessage(char* buf) {
memcpy(buf, kMessage, sizeof(kMessage) * sizeof(char)); // sizeof(kMessage) / sizeof(char)
}
This check may trigger on code using the arraysize macro. The following code is
working correctly but should be simplified by using only the ``sizeof``
operator.
.. code-block:: c++
extern Object objects[100];
void InitializeObjects() {
memset(objects, 0, arraysize(objects) * sizeof(Object)); // sizeof(objects)
}
Suspicious usage of 'sizeof(sizeof(...))'
-----------------------------------------
Getting the ``sizeof`` of a ``sizeof`` makes no sense and is typically an error
hidden through macros.
.. code-block:: c++
#define INT_SZ sizeof(int)
int buf[] = { 42 };
void getInt(int* dst) {
memcpy(dst, buf, sizeof(INT_SZ)); // sizeof(sizeof(int)) is suspicious.
}
Options
-------
.. option:: WarnOnSizeOfConstant
When `true`, the check will warn on an expression like
``sizeof(CONSTANT)``. Default is `true`.
.. option:: WarnOnSizeOfIntegerExpression
When `true`, the check will warn on an expression like ``sizeof(expr)``
where the expression results in an integer. Default is `false`.
.. option:: WarnOnSizeOfThis
When `true`, the check will warn on an expression like ``sizeof(this)``.
Default is `true`.
.. option:: WarnOnSizeOfCompareToConstant
When `true`, the check will warn on an expression like
``sizeof(epxr) <= k`` for a suspicious constant `k` while `k` is `0` or
greater than `0x8000`. Default is `true`.
.. title:: clang-tidy - bugprone-spuriously-wake-up-functions
bugprone-spuriously-wake-up-functions
=====================================
Finds ``cnd_wait``, ``cnd_timedwait``, ``wait``, ``wait_for``, or
``wait_until`` function calls when the function is not invoked from a loop
that checks whether a condition predicate holds or the function has a
condition parameter.
.. code-block: c++
if (condition_predicate) {
condition.wait(lk);
}
.. code-block: c
if (condition_predicate) {
if (thrd_success != cnd_wait(&condition, &lock)) {
}
}
This check corresponds to the CERT C++ Coding Standard rule
`CON54-CPP. Wrap functions that can spuriously wake up in a loop
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/CON54-CPP.+Wrap+functions+that+can+spuriously+wake+up+in+a+loop>`_.
and CERT C Coding Standard rule
`CON36-C. Wrap functions that can spuriously wake up in a loop
<https://wiki.sei.cmu.edu/confluence/display/c/CON36-C.+Wrap+functions+that+can+spuriously+wake+up+in+a+loop>`_.
.. title:: clang-tidy - bugprone-string-constructor
bugprone-string-constructor
===========================
Finds string constructors that are suspicious and probably errors.
A common mistake is to swap parameters to the 'fill' string-constructor.
Examples:
.. code-block:: c++
std::string str('x', 50); // should be str(50, 'x')
Calling the string-literal constructor with a length bigger than the literal is
suspicious and adds extra random characters to the string.
Examples:
.. code-block:: c++
std::string("test", 200); // Will include random characters after "test".
std::string_view("test", 200);
Creating an empty string from constructors with parameters is considered
suspicious. The programmer should use the empty constructor instead.
Examples:
.. code-block:: c++
std::string("test", 0); // Creation of an empty string.
std::string_view("test", 0);
Options
-------
.. option:: WarnOnLargeLength
When `true`, the check will warn on a string with a length greater than
:option:`LargeLengthThreshold`. Default is `true`.
.. option:: LargeLengthThreshold
An integer specifying the large length threshold. Default is `0x800000`.
.. option:: StringNames
Default is `::std::basic_string;::std::basic_string_view`.
Semicolon-delimited list of class names to apply this check to.
By default `::std::basic_string` applies to ``std::string`` and
``std::wstring``. Set to e.g. `::std::basic_string;llvm::StringRef;QString`
to perform this check on custom classes.
.. title:: clang-tidy - bugprone-string-integer-assignment
bugprone-string-integer-assignment
==================================
The check finds assignments of an integer to ``std::basic_string<CharT>``
(``std::string``, ``std::wstring``, etc.). The source of the problem is the
following assignment operator of ``std::basic_string<CharT>``:
.. code-block:: c++
basic_string& operator=( CharT ch );
Numeric types can be implicitly casted to character types.
.. code-block:: c++
std::string s;
int x = 5965;
s = 6;
s = x;
Use the appropriate conversion functions or character literals.
.. code-block:: c++
std::string s;
int x = 5965;
s = '6';
s = std::to_string(x);
In order to suppress false positives, use an explicit cast.
.. code-block:: c++
std::string s;
s = static_cast<char>(6);
.. title:: clang-tidy - bugprone-string-literal-with-embedded-nul
bugprone-string-literal-with-embedded-nul
=========================================
Finds occurrences of string literal with embedded NUL character and validates
their usage.
Invalid escaping
----------------
Special characters can be escaped within a string literal by using their
hexadecimal encoding like ``\x42``. A common mistake is to escape them
like this ``\0x42`` where the ``\0`` stands for the NUL character.
.. code-block:: c++
const char* Example[] = "Invalid character: \0x12 should be \x12";
const char* Bytes[] = "\x03\0x02\0x01\0x00\0xFF\0xFF\0xFF";
Truncated literal
-----------------
String-like classes can manipulate strings with embedded NUL as they are keeping
track of the bytes and the length. This is not the case for a ``char*``
(NUL-terminated) string.
A common mistake is to pass a string-literal with embedded NUL to a string
constructor expecting a NUL-terminated string. The bytes after the first NUL
character are truncated.
.. code-block:: c++
std::string str("abc\0def"); // "def" is truncated
str += "\0"; // This statement is doing nothing
if (str == "\0abc") return; // This expression is always true
.. title:: clang-tidy - bugprone-suspicious-enum-usage
bugprone-suspicious-enum-usage
==============================
The checker detects various cases when an enum is probably misused (as a bitmask
).
1. When "ADD" or "bitwise OR" is used between two enum which come from different
types and these types value ranges are not disjoint.
The following cases will be investigated only using :option:`StrictMode`. We
regard the enum as a (suspicious)
bitmask if the three conditions below are true at the same time:
* at most half of the elements of the enum are non pow-of-2 numbers (because of
short enumerations)
* there is another non pow-of-2 number than the enum constant representing all
choices (the result "bitwise OR" operation of all enum elements)
* enum type variable/enumconstant is used as an argument of a `+` or "bitwise OR
" operator
So whenever the non pow-of-2 element is used as a bitmask element we diagnose a
misuse and give a warning.
2. Investigating the right hand side of `+=` and `|=` operator.
3. Check only the enum value side of a `|` and `+` operator if one of them is not
enum val.
4. Check both side of `|` or `+` operator where the enum values are from the
same enum type.
Examples:
.. code-block:: c++
enum { A, B, C };
enum { D, E, F = 5 };
enum { G = 10, H = 11, I = 12 };
unsigned flag;
flag =
A |
H; // OK, disjoint value intervals in the enum types ->probably good use.
flag = B | F; // Warning, have common values so they are probably misused.
// Case 2:
enum Bitmask {
A = 0,
B = 1,
C = 2,
D = 4,
E = 8,
F = 16,
G = 31 // OK, real bitmask.
};
enum Almostbitmask {
AA = 0,
BB = 1,
CC = 2,
DD = 4,
EE = 8,
FF = 16,
GG // Problem, forgot to initialize.
};
unsigned flag = 0;
flag |= E; // OK.
flag |=
EE; // Warning at the decl, and note that it was used here as a bitmask.
Options
-------
.. option:: StrictMode
Default value: 0.
When non-null the suspicious bitmask usage will be investigated additionally
to the different enum usage check.
.. title:: clang-tidy - bugprone-suspicious-include
bugprone-suspicious-include
===========================
The check detects various cases when an include refers to what appears to be an
implementation file, which often leads to hard-to-track-down ODR violations.
Examples:
.. code-block:: c++
#include "Dinosaur.hpp" // OK, .hpp files tend not to have definitions.
#include "Pterodactyl.h" // OK, .h files tend not to have definitions.
#include "Velociraptor.cpp" // Warning, filename is suspicious.
#include_next <stdio.c> // Warning, filename is suspicious.
Options
-------
.. option:: HeaderFileExtensions
Default value: ``";h;hh;hpp;hxx"``
A semicolon-separated list of filename extensions of header files (the
filename extensions should not contain a "." prefix). For extension-less
header files, use an empty string or leave an empty string between ";"
if there are other filename extensions.
.. option:: ImplementationFileExtensions
Default value: ``"c;cc;cpp;cxx"``
Likewise, a semicolon-separated list of filename extensions of
implementation files.
.. title:: clang-tidy - bugprone-suspicious-memset-usage
bugprone-suspicious-memset-usage
================================
This check finds ``memset()`` calls with potential mistakes in their arguments.
Considering the function as ``void* memset(void* destination, int fill_value,
size_t byte_count)``, the following cases are covered:
**Case 1: Fill value is a character ``'0'``**
Filling up a memory area with ASCII code 48 characters is not customary,
possibly integer zeroes were intended instead.
The check offers a replacement of ``'0'`` with ``0``. Memsetting character
pointers with ``'0'`` is allowed.
**Case 2: Fill value is truncated**
Memset converts ``fill_value`` to ``unsigned char`` before using it. If
``fill_value`` is out of unsigned character range, it gets truncated
and memory will not contain the desired pattern.
**Case 3: Byte count is zero**
Calling memset with a literal zero in its ``byte_count`` argument is likely
to be unintended and swapped with ``fill_value``. The check offers to swap
these two arguments.
Corresponding cpplint.py check name: ``runtime/memset``.
Examples:
.. code-block:: c++
void foo() {
int i[5] = {1, 2, 3, 4, 5};
int *ip = i;
char c = '1';
char *cp = &c;
int v = 0;
// Case 1
memset(ip, '0', 1); // suspicious
memset(cp, '0', 1); // OK
// Case 2
memset(ip, 0xabcd, 1); // fill value gets truncated
memset(ip, 0x00, 1); // OK
// Case 3
memset(ip, sizeof(int), v); // zero length, potentially swapped
memset(ip, 0, 1); // OK
}
.. title:: clang-tidy - bugprone-suspicious-missing-comma
bugprone-suspicious-missing-comma
=================================
String literals placed side-by-side are concatenated at translation phase 6
(after the preprocessor). This feature is used to represent long string
literal on multiple lines.
For instance, the following declarations are equivalent:
.. code-block:: c++
const char* A[] = "This is a test";
const char* B[] = "This" " is a " "test";
A common mistake done by programmers is to forget a comma between two string
literals in an array initializer list.
.. code-block:: c++
const char* Test[] = {
"line 1",
"line 2" // Missing comma!
"line 3",
"line 4",
"line 5"
};
The array contains the string "line 2line3" at offset 1 (i.e. Test[1]). Clang
won't generate warnings at compile time.
This check may warn incorrectly on cases like:
.. code-block:: c++
const char* SupportedFormat[] = {
"Error %s",
"Code " PRIu64, // May warn here.
"Warning %s",
};
Options
-------
.. option:: SizeThreshold
An unsigned integer specifying the minimum size of a string literal to be
considered by the check. Default is ``5U``.
.. option:: RatioThreshold
A string specifying the maximum threshold ratio [0, 1.0] of suspicious string
literals to be considered. Default is ``".2"``.
.. option:: MaxConcatenatedTokens
An unsigned integer specifying the maximum number of concatenated tokens.
Default is ``5U``.
.. title:: clang-tidy - bugprone-suspicious-semicolon
bugprone-suspicious-semicolon
=============================
Finds most instances of stray semicolons that unexpectedly alter the meaning of
the code. More specifically, it looks for ``if``, ``while``, ``for`` and
``for-range`` statements whose body is a single semicolon, and then analyzes the
context of the code (e.g. indentation) in an attempt to determine whether that
is intentional.
.. code-block:: c++
if (x < y);
{
x++;
}
Here the body of the ``if`` statement consists of only the semicolon at the end
of the first line, and `x` will be incremented regardless of the condition.
.. code-block:: c++
while ((line = readLine(file)) != NULL);
processLine(line);
As a result of this code, `processLine()` will only be called once, when the
``while`` loop with the empty body exits with `line == NULL`. The indentation of
the code indicates the intention of the programmer.
.. code-block:: c++
if (x >= y);
x -= y;
While the indentation does not imply any nesting, there is simply no valid
reason to have an `if` statement with an empty body (but it can make sense for
a loop). So this check issues a warning for the code above.
To solve the issue remove the stray semicolon or in case the empty body is
intentional, reflect this using code indentation or put the semicolon in a new
line. For example:
.. code-block:: c++
while (readWhitespace());
Token t = readNextToken();
Here the second line is indented in a way that suggests that it is meant to be
the body of the `while` loop - whose body is in fact empty, because of the
semicolon at the end of the first line.
Either remove the indentation from the second line:
.. code-block:: c++
while (readWhitespace());
Token t = readNextToken();
... or move the semicolon from the end of the first line to a new line:
.. code-block:: c++
while (readWhitespace())
;
Token t = readNextToken();
In this case the check will assume that you know what you are doing, and will
not raise a warning.
.. title:: clang-tidy - bugprone-suspicious-string-compare
bugprone-suspicious-string-compare
==================================
Find suspicious usage of runtime string comparison functions.
This check is valid in C and C++.
Checks for calls with implicit comparator and proposed to explicitly add it.
.. code-block:: c++
if (strcmp(...)) // Implicitly compare to zero
if (!strcmp(...)) // Won't warn
if (strcmp(...) != 0) // Won't warn
Checks that compare function results (i,e, ``strcmp``) are compared to valid
constant. The resulting value is
.. code::
< 0 when lower than,
> 0 when greater than,
== 0 when equals.
A common mistake is to compare the result to `1` or `-1`.
.. code-block:: c++
if (strcmp(...) == -1) // Incorrect usage of the returned value.
Additionally, the check warns if the results value is implicitly cast to a
*suspicious* non-integer type. It's happening when the returned value is used in
a wrong context.
.. code-block:: c++
if (strcmp(...) < 0.) // Incorrect usage of the returned value.
Options
-------
.. option:: WarnOnImplicitComparison
When `true`, the check will warn on implicit comparison. `true` by default.
.. option:: WarnOnLogicalNotComparison
When `true`, the check will warn on logical not comparison. `false` by default.
.. option:: StringCompareLikeFunctions
A string specifying the comma-separated names of the extra string comparison
functions. Default is an empty string.
The check will detect the following string comparison functions:
`__builtin_memcmp`, `__builtin_strcasecmp`, `__builtin_strcmp`,
`__builtin_strncasecmp`, `__builtin_strncmp`, `_mbscmp`, `_mbscmp_l`,
`_mbsicmp`, `_mbsicmp_l`, `_mbsnbcmp`, `_mbsnbcmp_l`, `_mbsnbicmp`,
`_mbsnbicmp_l`, `_mbsncmp`, `_mbsncmp_l`, `_mbsnicmp`, `_mbsnicmp_l`,
`_memicmp`, `_memicmp_l`, `_stricmp`, `_stricmp_l`, `_strnicmp`,
`_strnicmp_l`, `_wcsicmp`, `_wcsicmp_l`, `_wcsnicmp`, `_wcsnicmp_l`,
`lstrcmp`, `lstrcmpi`, `memcmp`, `memicmp`, `strcasecmp`, `strcmp`,
`strcmpi`, `stricmp`, `strncasecmp`, `strncmp`, `strnicmp`, `wcscasecmp`,
`wcscmp`, `wcsicmp`, `wcsncmp`, `wcsnicmp`, `wmemcmp`.
.. title:: clang-tidy - bugprone-swapped-arguments
bugprone-swapped-arguments
==========================
Finds potentially swapped arguments by looking at implicit conversions.
.. title:: clang-tidy - bugprone-terminating-continue
bugprone-terminating-continue
=============================
Detects ``do while`` loops with a condition always evaluating to false that
have a ``continue`` statement, as this ``continue`` terminates the loop
effectively.
.. code-block:: c++
void f() {
do {
// some code
continue; // terminating continue
// some other code
} while(false);
.. title:: clang-tidy - bugprone-throw-keyword-missing
bugprone-throw-keyword-missing
==============================
Warns about a potentially missing ``throw`` keyword. If a temporary object is created, but the
object's type derives from (or is the same as) a class that has 'EXCEPTION', 'Exception' or
'exception' in its name, we can assume that the programmer's intention was to throw that object.
Example:
.. code-block:: c++
void f(int i) {
if (i < 0) {
// Exception is created but is not thrown.
std::runtime_error("Unexpected argument");
}
}
.. title:: clang-tidy - bugprone-too-small-loop-variable
bugprone-too-small-loop-variable
================================
Detects those ``for`` loops that have a loop variable with a "too small" type
which means this type can't represent all values which are part of the
iteration range.
.. code-block:: c++
int main() {
long size = 294967296l;
for (short i = 0; i < size; ++i) {}
}
This ``for`` loop is an infinite loop because the ``short`` type can't represent
all values in the ``[0..size]`` interval.
In a real use case size means a container's size which depends on the user input.
.. code-block:: c++
int doSomething(const std::vector& items) {
for (short i = 0; i < items.size(); ++i) {}
}
This algorithm works for small amount of objects, but will lead to freeze for a
a larger user input.
.. option:: MagnitudeBitsUpperLimit
Upper limit for the magnitude bits of the loop variable. If it's set the check
filters out those catches in which the loop variable's type has more magnitude
bits as the specified upper limit. The default value is 16.
For example, if the user sets this option to 31 (bits), then a 32-bit ``unsigend int``
is ignored by the check, however a 32-bit ``int`` is not (A 32-bit ``signed int``
has 31 magnitude bits).
.. code-block:: c++
int main() {
long size = 294967296l;
for (unsigned i = 0; i < size; ++i) {} // no warning with MagnitudeBitsUpperLimit = 31 on a system where unsigned is 32-bit
for (int i = 0; i < size; ++i) {} // warning with MagnitudeBitsUpperLimit = 31 on a system where int is 32-bit
}
.. title:: clang-tidy - bugprone-undefined-memory-manipulation
bugprone-undefined-memory-manipulation
======================================
Finds calls of memory manipulation functions ``memset()``, ``memcpy()`` and
``memmove()`` on not TriviallyCopyable objects resulting in undefined behavior.
.. title:: clang-tidy - bugprone-undelegated-constructor
bugprone-undelegated-constructor
================================
Finds creation of temporary objects in constructors that look like a
function call to another constructor of the same class.
The user most likely meant to use a delegating constructor or base class
initializer.
.. title:: clang-tidy - bugprone-unhandled-exception-at-new
bugprone-unhandled-exception-at-new
===================================
Finds calls to ``new`` with missing exception handler for ``std::bad_alloc``.
.. code-block:: c++
int *f() noexcept {
int *p = new int[1000];
// ...
return p;
}
Calls to ``new`` can throw exceptions of type ``std::bad_alloc`` that should
be handled by the code. Alternatively, the nonthrowing form of ``new`` can be
used. The check verifies that the exception is handled in the function
that calls ``new``, unless a nonthrowing version is used or the exception
is allowed to propagate out of the function (exception handler is checked for
types ``std::bad_alloc``, ``std::exception``, and catch-all handler).
The check assumes that any user-defined ``operator new`` is either
``noexcept`` or may throw an exception of type ``std::bad_alloc`` (or derived
from it). Other exception types or exceptions occuring in the objects's
constructor are not taken into account.
.. title:: clang-tidy - bugprone-unhandled-self-assignment
bugprone-unhandled-self-assignment
==================================
`cert-oop54-cpp` redirects here as an alias for this check. For the CERT alias,
the `WarnOnlyIfThisHasSuspiciousField` option is set to `false`.
Finds user-defined copy assignment operators which do not protect the code
against self-assignment either by checking self-assignment explicitly or
using the copy-and-swap or the copy-and-move method.
By default, this check searches only those classes which have any pointer or C array field
to avoid false positives. In case of a pointer or a C array, it's likely that self-copy
assignment breaks the object if the copy assignment operator was not written with care.
See also:
`OOP54-CPP. Gracefully handle self-copy assignment
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP54-CPP.+Gracefully+handle+self-copy+assignment>`_
A copy assignment operator must prevent that self-copy assignment ruins the
object state. A typical use case is when the class has a pointer field
and the copy assignment operator first releases the pointed object and
then tries to assign it:
.. code-block:: c++
class T {
int* p;
public:
T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
~T() { delete p; }
// ...
T& operator=(const T &rhs) {
delete p;
p = new int(*rhs.p);
return *this;
}
};
There are two common C++ patterns to avoid this problem. The first is
the self-assignment check:
.. code-block:: c++
class T {
int* p;
public:
T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
~T() { delete p; }
// ...
T& operator=(const T &rhs) {
if(this == &rhs)
return *this;
delete p;
p = new int(*rhs.p);
return *this;
}
};
The second one is the copy-and-swap method when we create a temporary copy
(using the copy constructor) and then swap this temporary object with ``this``:
.. code-block:: c++
class T {
int* p;
public:
T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
~T() { delete p; }
// ...
void swap(T &rhs) {
using std::swap;
swap(p, rhs.p);
}
T& operator=(const T &rhs) {
T(rhs).swap(*this);
return *this;
}
};
There is a third pattern which is less common. Let's call it the copy-and-move method
when we create a temporary copy (using the copy constructor) and then move this
temporary object into ``this`` (needs a move assignment operator):
.. code-block:: c++
class T {
int* p;
public:
T(const T &rhs) : p(rhs.p ? new int(*rhs.p) : nullptr) {}
~T() { delete p; }
// ...
T& operator=(const T &rhs) {
T t = rhs;
*this = std::move(t);
return *this;
}
T& operator=(T &&rhs) {
p = rhs.p;
rhs.p = nullptr;
return *this;
}
};
.. option:: WarnOnlyIfThisHasSuspiciousField
When `true`, the check will warn only if the container class of the copy assignment operator
has any suspicious fields (pointer or C array). This option is set to `true` by default.
.. title:: clang-tidy - bugprone-unused-raii
bugprone-unused-raii
====================
Finds temporaries that look like RAII objects.
The canonical example for this is a scoped lock.
.. code-block:: c++
{
scoped_lock(&global_mutex);
critical_section();
}
The destructor of the scoped_lock is called before the ``critical_section`` is
entered, leaving it unprotected.
We apply a number of heuristics to reduce the false positive count of this
check:
- Ignore code expanded from macros. Testing frameworks make heavy use of this.
- Ignore types with trivial destructors. They are very unlikely to be RAII
objects and there's no difference when they are deleted.
- Ignore objects at the end of a compound statement (doesn't change behavior).
- Ignore objects returned from a call.
.. title:: clang-tidy - bugprone-unused-return-value
bugprone-unused-return-value
============================
Warns on unused function return values. The checked functions can be configured.
Options
-------
.. option:: CheckedFunctions
Semicolon-separated list of functions to check. Defaults to
``::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique;::std::unique_ptr::release;::std::basic_string::empty;::std::vector::empty``.
This means that the calls to following functions are checked by default:
- ``std::async()``. Not using the return value makes the call synchronous.
- ``std::launder()``. Not using the return value usually means that the
function interface was misunderstood by the programmer. Only the returned
pointer is "laundered", not the argument.
- ``std::remove()``, ``std::remove_if()`` and ``std::unique()``. The returned
iterator indicates the boundary between elements to keep and elements to be
removed. Not using the return value means that the information about which
elements to remove is lost.
- ``std::unique_ptr::release()``. Not using the return value can lead to
resource leaks if the same pointer isn't stored anywhere else. Often,
ignoring the ``release()`` return value indicates that the programmer
confused the function with ``reset()``.
- ``std::basic_string::empty()`` and ``std::vector::empty()``. Not using the
return value often indicates that the programmer confused the function with
``clear()``.
.. title:: clang-tidy - bugprone-use-after-move
bugprone-use-after-move
=======================
Warns if an object is used after it has been moved, for example:
.. code-block:: c++
std::string str = "Hello, world!\n";
std::vector<std::string> messages;
messages.emplace_back(std::move(str));
std::cout << str;
The last line will trigger a warning that ``str`` is used after it has been
moved.
The check does not trigger a warning if the object is reinitialized after the
move and before the use. For example, no warning will be output for this code:
.. code-block:: c++
messages.emplace_back(std::move(str));
str = "Greetings, stranger!\n";
std::cout << str;
Subsections below explain more precisely what exactly the check considers to be
a move, use, and reinitialization.
The check takes control flow into account. A warning is only emitted if the use
can be reached from the move. This means that the following code does not
produce a warning:
.. code-block:: c++
if (condition) {
messages.emplace_back(std::move(str));
} else {
std::cout << str;
}
On the other hand, the following code does produce a warning:
.. code-block:: c++
for (int i = 0; i < 10; ++i) {
std::cout << str;
messages.emplace_back(std::move(str));
}
(The use-after-move happens on the second iteration of the loop.)
In some cases, the check may not be able to detect that two branches are
mutually exclusive. For example (assuming that ``i`` is an int):
.. code-block:: c++
if (i == 1) {
messages.emplace_back(std::move(str));
}
if (i == 2) {
std::cout << str;
}
In this case, the check will erroneously produce a warning, even though it is
not possible for both the move and the use to be executed. More formally, the
analysis is `flow-sensitive but not path-sensitive
<https://en.wikipedia.org/wiki/Data-flow_analysis#Sensitivities>`_.
Silencing erroneous warnings
----------------------------
An erroneous warning can be silenced by reinitializing the object after the
move:
.. code-block:: c++
if (i == 1) {
messages.emplace_back(std::move(str));
str = "";
}
if (i == 2) {
std::cout << str;
}
If you want to avoid the overhead of actually reinitializing the object, you can
create a dummy function that causes the check to assume the object was
reinitialized:
.. code-block:: c++
template <class T>
void IS_INITIALIZED(T&) {}
You can use this as follows:
.. code-block:: c++
if (i == 1) {
messages.emplace_back(std::move(str));
}
if (i == 2) {
IS_INITIALIZED(str);
std::cout << str;
}
The check will not output a warning in this case because passing the object to a
function as a non-const pointer or reference counts as a reinitialization (see section
`Reinitialization`_ below).
Unsequenced moves, uses, and reinitializations
----------------------------------------------
In many cases, C++ does not make any guarantees about the order in which
sub-expressions of a statement are evaluated. This means that in code like the
following, it is not guaranteed whether the use will happen before or after the
move:
.. code-block:: c++
void f(int i, std::vector<int> v);
std::vector<int> v = { 1, 2, 3 };
f(v[1], std::move(v));
In this kind of situation, the check will note that the use and move are
unsequenced.
The check will also take sequencing rules into account when reinitializations
occur in the same statement as moves or uses. A reinitialization is only
considered to reinitialize a variable if it is guaranteed to be evaluated after
the move and before the use.
Move
----
The check currently only considers calls of ``std::move`` on local variables or
function parameters. It does not check moves of member variables or global
variables.
Any call of ``std::move`` on a variable is considered to cause a move of that
variable, even if the result of ``std::move`` is not passed to an rvalue
reference parameter.
This means that the check will flag a use-after-move even on a type that does
not define a move constructor or move assignment operator. This is intentional.
Developers may use ``std::move`` on such a type in the expectation that the type
will add move semantics in the future. If such a ``std::move`` has the potential
to cause a use-after-move, we want to warn about it even if the type does not
implement move semantics yet.
Furthermore, if the result of ``std::move`` *is* passed to an rvalue reference
parameter, this will always be considered to cause a move, even if the function
that consumes this parameter does not move from it, or if it does so only
conditionally. For example, in the following situation, the check will assume
that a move always takes place:
.. code-block:: c++
std::vector<std::string> messages;
void f(std::string &&str) {
// Only remember the message if it isn't empty.
if (!str.empty()) {
messages.emplace_back(std::move(str));
}
}
std::string str = "";
f(std::move(str));
The check will assume that the last line causes a move, even though, in this
particular case, it does not. Again, this is intentional.
There is one special case: A call to ``std::move`` inside a ``try_emplace`` call
is conservatively assumed not to move. This is to avoid spurious warnings, as
the check has no way to reason about the ``bool`` returned by ``try_emplace``.
When analyzing the order in which moves, uses and reinitializations happen (see
section `Unsequenced moves, uses, and reinitializations`_), the move is assumed
to occur in whichever function the result of the ``std::move`` is passed to.
Use
---
Any occurrence of the moved variable that is not a reinitialization (see below)
is considered to be a use.
An exception to this are objects of type ``std::unique_ptr``,
``std::shared_ptr`` and ``std::weak_ptr``, which have defined move behavior
(objects of these classes are guaranteed to be empty after they have been moved
from). Therefore, an object of these classes will only be considered to be used
if it is dereferenced, i.e. if ``operator*``, ``operator->`` or ``operator[]``
(in the case of ``std::unique_ptr<T []>``) is called on it.
If multiple uses occur after a move, only the first of these is flagged.
Reinitialization
----------------
The check considers a variable to be reinitialized in the following cases:
- The variable occurs on the left-hand side of an assignment.
- The variable is passed to a function as a non-const pointer or non-const
lvalue reference. (It is assumed that the variable may be an out-parameter
for the function.)
- ``clear()`` or ``assign()`` is called on the variable and the variable is of
one of the standard container types ``basic_string``, ``vector``, ``deque``,
``forward_list``, ``list``, ``set``, ``map``, ``multiset``, ``multimap``,
``unordered_set``, ``unordered_map``, ``unordered_multiset``,
``unordered_multimap``.
- ``reset()`` is called on the variable and the variable is of type
``std::unique_ptr``, ``std::shared_ptr`` or ``std::weak_ptr``.
- A member function marked with the ``[[clang::reinitializes]]`` attribute is
called on the variable.
If the variable in question is a struct and an individual member variable of
that struct is written to, the check does not consider this to be a
reinitialization -- even if, eventually, all member variables of the struct are
written to. For example:
.. code-block:: c++
struct S {
std::string str;
int i;
};
S s = { "Hello, world!\n", 42 };
S s_other = std::move(s);
s.str = "Lorem ipsum";
s.i = 99;
The check will not consider ``s`` to be reinitialized after the last line;
instead, the line that assigns to ``s.str`` will be flagged as a use-after-move.
This is intentional as this pattern of reinitializing a struct is error-prone.
For example, if an additional member variable is added to ``S``, it is easy to
forget to add the reinitialization for this additional member. Instead, it is
safer to assign to the entire struct in one go, and this will also avoid the
use-after-move warning.
.. title:: clang-tidy - bugprone-virtual-near-miss
bugprone-virtual-near-miss
==========================
Warn if a function is a near miss (ie. the name is very similar and the function
signature is the same) to a virtual function from a base class.
Example:
.. code-block:: c++
struct Base {
virtual void func();
};
struct Derived : Base {
virtual funk();
// warning: 'Derived::funk' has a similar name and the same signature as virtual method 'Base::func'; did you mean to override it?
};
.. title:: clang-tidy - cert-con36-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-spuriously-wake-up-functions.html
cert-con36-c
============
The cert-con36-c check is an alias, please see
`bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_
for more information.
.. title:: clang-tidy - cert-con54-cpp
.. meta::
:http-equiv=refresh: 5;URL=bugprone-spuriously-wake-up-functions.html
cert-con54-cpp
==============
The cert-con54-cpp check is an alias, please see
`bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_
for more information.
.. title:: clang-tidy - cert-dcl03-c
.. meta::
:http-equiv=refresh: 5;URL=misc-static-assert.html
cert-dcl03-c
============
The cert-dcl03-c check is an alias, please see
`misc-static-assert <misc-static-assert.html>`_ for more information.
.. title:: clang-tidy - cert-dcl16-c
.. meta::
:http-equiv=refresh: 5;URL=readability-uppercase-literal-suffix.html
cert-dcl16-c
============
The cert-dcl16-c check is an alias, please see
`readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_ for more information.
.. title:: clang-tidy - cert-dcl21-cpp
cert-dcl21-cpp
==============
This check flags postfix ``operator++`` and ``operator--`` declarations
if the return type is not a const object. This also warns if the return type
is a reference type.
The object returned by a postfix increment or decrement operator is supposed
to be a snapshot of the object's value prior to modification. With such an
implementation, any modifications made to the resulting object from calling
operator++(int) would be modifying a temporary object. Thus, such an
implementation of a postfix increment or decrement operator should instead
return a const object, prohibiting accidental mutation of a temporary object.
Similarly, it is unexpected for the postfix operator to return a reference to
its previous state, and any subsequent modifications would be operating on a
stale object.
This check corresponds to the CERT C++ Coding Standard recommendation
DCL21-CPP. Overloaded postfix increment and decrement operators should return a
const object. However, all of the CERT recommendations have been removed from
public view, and so their justification for the behavior of this check requires
an account on their wiki to view... title:: clang-tidy - cert-dcl37-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-reserved-identifier.html
cert-dcl37-c
============
The cert-dcl37-c check is an alias, please see
`bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_ for more
information.
.. title:: clang-tidy - cert-dcl50-cpp
cert-dcl50-cpp
==============
This check flags all function definitions (but not declarations) of C-style
variadic functions.
This check corresponds to the CERT C++ Coding Standard rule
`DCL50-CPP. Do not define a C-style variadic function
<https://www.securecoding.cert.org/confluence/display/cplusplus/DCL50-CPP.+Do+not+define+a+C-style+variadic+function>`_.
.. title:: clang-tidy - cert-dcl51-cpp
.. meta::
:http-equiv=refresh: 5;URL=bugprone-reserved-identifier.html
cert-dcl51-cpp
==============
The cert-dcl51-cpp check is an alias, please see
`bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_ for more
information.
.. title:: clang-tidy - cert-dcl54-cpp
.. meta::
:http-equiv=refresh: 5;URL=misc-new-delete-overloads.html
cert-dcl54-cpp
==============
The cert-dcl54-cpp check is an alias, please see
`misc-new-delete-overloads <misc-new-delete-overloads.html>`_ for more
information.
.. title:: clang-tidy - cert-dcl58-cpp
cert-dcl58-cpp
==============
Modification of the ``std`` or ``posix`` namespace can result in undefined
behavior.
This check warns for such modifications.
Examples:
.. code-block:: c++
namespace std {
int x; // May cause undefined behavior.
}
This check corresponds to the CERT C++ Coding Standard rule
`DCL58-CPP. Do not modify the standard namespaces
<https://www.securecoding.cert.org/confluence/display/cplusplus/DCL58-CPP.+Do+not+modify+the+standard+namespaces>`_.
.. title:: clang-tidy - cert-dcl59-cpp
.. meta::
:http-equiv=refresh: 5;URL=google-build-namespaces.html
cert-dcl59-cpp
==============
The cert-dcl59-cpp check is an alias, please see
`google-build-namespaces <google-build-namespaces.html>`_ for more information.
.. title:: clang-tidy - cert-env33-c
cert-env33-c
============
This check flags calls to ``system()``, ``popen()``, and ``_popen()``, which
execute a command processor. It does not flag calls to ``system()`` with a null
pointer argument, as such a call checks for the presence of a command processor
but does not actually attempt to execute a command.
This check corresponds to the CERT C Coding Standard rule
`ENV33-C. Do not call system()
<https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=2130132>`_.
.. title:: clang-tidy - cert-err09-cpp
.. meta::
:http-equiv=refresh: 5;URL=misc-throw-by-value-catch-by-reference.html
cert-err09-cpp
==============
The cert-err09-cpp check is an alias, please see
`misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_
for more information.
This check corresponds to the CERT C++ Coding Standard recommendation
ERR09-CPP. Throw anonymous temporaries. However, all of the CERT recommendations
have been removed from public view, and so their justification for the behavior
of this check requires an account on their wiki to view... title:: clang-tidy - cert-err34-c
cert-err34-c
============
This check flags calls to string-to-number conversion functions that do not
verify the validity of the conversion, such as ``atoi()`` or ``scanf()``. It
does not flag calls to ``strtol()``, or other, related conversion functions that
do perform better error checking.
.. code-block:: c
#include <stdlib.h>
void func(const char *buff) {
int si;
if (buff) {
si = atoi(buff); /* 'atoi' used to convert a string to an integer, but function will
not report conversion errors; consider using 'strtol' instead. */
} else {
/* Handle error */
}
}
This check corresponds to the CERT C Coding Standard rule
`ERR34-C. Detect errors when converting a string to a number
<https://www.securecoding.cert.org/confluence/display/c/ERR34-C.+Detect+errors+when+converting+a+string+to+a+number>`_.
.. title:: clang-tidy - cert-err52-cpp
cert-err52-cpp
==============
This check flags all call expressions involving ``setjmp()`` and ``longjmp()``.
This check corresponds to the CERT C++ Coding Standard rule
`ERR52-CPP. Do not use setjmp() or longjmp()
<https://www.securecoding.cert.org/confluence/pages/viewpage.action?pageId=1834>`_.
.. title:: clang-tidy - cert-err58-cpp
cert-err58-cpp
==============
This check flags all ``static`` or ``thread_local`` variable declarations where
the initializer for the object may throw an exception.
This check corresponds to the CERT C++ Coding Standard rule
`ERR58-CPP. Handle all exceptions thrown before main() begins executing
<https://www.securecoding.cert.org/confluence/display/cplusplus/ERR58-CPP.+Handle+all+exceptions+thrown+before+main%28%29+begins+executing>`_.
.. title:: clang-tidy - cert-err60-cpp
cert-err60-cpp
==============
This check flags all throw expressions where the exception object is not nothrow
copy constructible.
This check corresponds to the CERT C++ Coding Standard rule
`ERR60-CPP. Exception objects must be nothrow copy constructible
<https://www.securecoding.cert.org/confluence/display/cplusplus/ERR60-CPP.+Exception+objects+must+be+nothrow+copy+constructible>`_.
.. title:: clang-tidy - cert-err61-cpp
.. meta::
:http-equiv=refresh: 5;URL=misc-throw-by-value-catch-by-reference.html
cert-err61-cpp
==============
The cert-err61-cpp check is an alias, please see
`misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_
for more information.
.. title:: clang-tidy - cert-fio38-c
.. meta::
:http-equiv=refresh: 5;URL=misc-non-copyable-objects.html
cert-fio38-c
============
The cert-fio38-c check is an alias, please see
`misc-non-copyable-objects <misc-non-copyable-objects.html>`_ for more
information.
.. title:: clang-tidy - cert-flp30-c
cert-flp30-c
============
This check flags ``for`` loops where the induction expression has a
floating-point type.
This check corresponds to the CERT C Coding Standard rule
`FLP30-C. Do not use floating-point variables as loop counters
<https://www.securecoding.cert.org/confluence/display/c/FLP30-C.+Do+not+use+floating-point+variables+as+loop+counters>`_.
.. title:: clang-tidy - cert-mem57-cpp
cert-mem57-cpp
==============
This check flags uses of default ``operator new`` where the type has extended
alignment (an alignment greater than the fundamental alignment). (The default
``operator new`` is guaranteed to provide the correct alignment if the
requested alignment is less or equal to the fundamental alignment).
Only cases are detected (by design) where the ``operator new`` is not
user-defined and is not a placement new (the reason is that in these cases we
assume that the user provided the correct memory allocation).
This check corresponds to the CERT C++ Coding Standard rule
`MEM57-CPP. Avoid using default operator new for over-aligned types
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/MEM57-CPP.+Avoid+using+default+operator+new+for+over-aligned+types>`_.
.. title:: clang-tidy - cert-msc30-c
.. meta::
:http-equiv=refresh: 5;URL=cert-msc50-cpp.html
cert-msc30-c
============
The cert-msc30-c check is an alias, please see
`cert-msc50-cpp <cert-msc50-cpp.html>`_ for more information.
.. title:: clang-tidy - cert-msc32-c
.. meta::
:http-equiv=refresh: 5;URL=cert-msc51-cpp.html
cert-msc32-c
============
The cert-msc32-c check is an alias, please see
`cert-msc51-cpp <cert-msc51-cpp.html>`_ for more information.
.. title:: clang-tidy - cert-msc50-cpp
cert-msc50-cpp
==============
Pseudorandom number generators use mathematical algorithms to produce a sequence
of numbers with good statistical properties, but the numbers produced are not
genuinely random. The ``std::rand()`` function takes a seed (number), runs a
mathematical operation on it and returns the result. By manipulating the seed
the result can be predictable. This check warns for the usage of
``std::rand()``.
.. title:: clang-tidy - cert-msc51-cpp
cert-msc51-cpp
==============
This check flags all pseudo-random number engines, engine adaptor
instantiations and ``srand()`` when initialized or seeded with default argument,
constant expression or any user-configurable type. Pseudo-random number
engines seeded with a predictable value may cause vulnerabilities e.g. in
security protocols.
This is a CERT security rule, see
`MSC51-CPP. Ensure your random number generator is properly seeded
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/MSC51-CPP.+Ensure+your+random+number+generator+is+properly+seeded>`_ and
`MSC32-C. Properly seed pseudorandom number generators
<https://wiki.sei.cmu.edu/confluence/display/c/MSC32-C.+Properly+seed+pseudorandom+number+generators>`_.
Examples:
.. code-block:: c++
void foo() {
std::mt19937 engine1; // Diagnose, always generate the same sequence
std::mt19937 engine2(1); // Diagnose
engine1.seed(); // Diagnose
engine2.seed(1); // Diagnose
std::time_t t;
engine1.seed(std::time(&t)); // Diagnose, system time might be controlled by user
int x = atoi(argv[1]);
std::mt19937 engine3(x); // Will not warn
}
Options
-------
.. option:: DisallowedSeedTypes
A comma-separated list of the type names which are disallowed.
Default values are ``time_t``, ``std::time_t``.
.. title:: clang-tidy - cert-oop11-cpp
.. meta::
:http-equiv=refresh: 5;URL=performance-move-constructor-init.html
cert-oop11-cpp
==============
The cert-oop11-cpp check is an alias, please see
`performance-move-constructor-init <performance-move-constructor-init.html>`_
for more information.
This check corresponds to the CERT C++ Coding Standard recommendation
OOP11-CPP. Do not copy-initialize members or base classes from a move
constructor. However, all of the CERT recommendations have been removed from
public view, and so their justification for the behavior of this check requires
an account on their wiki to view... title:: clang-tidy - cert-oop54-cpp
.. meta::
:http-equiv=refresh: 5;URL=bugprone-unhandled-self-assignment.html
cert-oop54-cpp
==============
The cert-oop54-cpp check is an alias, please see
`bugprone-unhandled-self-assignment <bugprone-unhandled-self-assignment.html>`_
for more information.
.. title:: clang-tidy - cert-oop57-cpp
cert-oop57-cpp
==============
Flags use of the `C` standard library functions ``memset``, ``memcpy`` and
``memcmp`` and similar derivatives on non-trivial types.
Options
-------
.. option:: MemSetNames
Specify extra functions to flag that act similarily to ``memset``.
Specify names in a semicolon delimited list.
Default is an empty string.
The check will detect the following functions:
`memset`, `std::memset`.
.. option:: MemCpyNames
Specify extra functions to flag that act similarily to ``memcpy``.
Specify names in a semicolon delimited list.
Default is an empty string.
The check will detect the following functions:
`std::memcpy`, `memcpy`, `std::memmove`, `memmove`, `std::strcpy`,
`strcpy`, `memccpy`, `stpncpy`, `strncpy`.
.. option:: MemCmpNames
Specify extra functions to flag that act similarily to ``memcmp``.
Specify names in a semicolon delimited list.
Default is an empty string.
The check will detect the following functions:
`std::memcmp`, `memcmp`, `std::strcmp`, `strcmp`, `strncmp`.
This check corresponds to the CERT C++ Coding Standard rule
`OOP57-CPP. Prefer special member functions and overloaded operators to C
Standard Library functions
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP57-CPP.+Prefer+special+member+functions+and+overloaded+operators+to+C+Standard+Library+functions>`_.
.. title:: clang-tidy - cert-mutating-copy
cert-oop58-cpp
==============
Finds assignments to the copied object and its direct or indirect members
in copy constructors and copy assignment operators.
This check corresponds to the CERT C Coding Standard rule
`OOP58-CPP. Copy operations must not mutate the source object
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/OOP58-CPP.+Copy+operations+must+not+mutate+the+source+object>`_.
.. title:: clang-tidy - cert-pos44-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-bad-signal-to-kill-thread.html
cert-pos44-c
============
The cert-pos44-c check is an alias, please see
`bugprone-bad-signal-to-kill-thread <bugprone-bad-signal-to-kill-thread.html>`_ for more information.
.. title:: clang-tidy - cert-pos47-c
.. meta::
:http-equiv=refresh: 5;URL=concurrency-thread-canceltype-asynchronous.html
cert-pos47-c
============
The cert-pos47-c check is an alias, please see
`concurrency-thread-canceltype-asynchronous <concurrency-thread-canceltype-asynchronous.html>`_ for more information.
.. title:: clang-tidy - cert-sig30-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-signal-handler.html
cert-sig30-c
============
The cert-sig30-c check is an alias, please see
`bugprone-signal-handler <bugprone-signal-handler.html>`_
for more information.
.. title:: clang-tidy - cert-str34-c
.. meta::
:http-equiv=refresh: 5;URL=bugprone-signed-char-misuse.html
cert-str34-c
============
The cert-str34-c check is an alias, please see
`bugprone-signed-char-misuse <bugprone-signed-char-misuse.html>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.CallAndMessage
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-callandmessage
clang-analyzer-core.CallAndMessage
==================================
The clang-analyzer-core.CallAndMessage check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-callandmessage>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.DivideZero
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-dividezero
clang-analyzer-core.DivideZero
==============================
The clang-analyzer-core.DivideZero check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-dividezero>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.DynamicTypePropagation
clang-analyzer-core.DynamicTypePropagation
==========================================
Generate dynamic type information
.. title:: clang-tidy - clang-analyzer-core.NonNullParamChecker
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-nonnullparamchecker
clang-analyzer-core.NonNullParamChecker
=======================================
The clang-analyzer-core.NonNullParamChecker check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-nonnullparamchecker>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.NullDereference
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-nulldereference
clang-analyzer-core.NullDereference
===================================
The clang-analyzer-core.NullDereference check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-nulldereference>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.StackAddressEscape
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-stackaddressescape
clang-analyzer-core.StackAddressEscape
======================================
The clang-analyzer-core.StackAddressEscape check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-stackaddressescape>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.UndefinedBinaryOperatorResult
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-undefinedbinaryoperatorresult
clang-analyzer-core.UndefinedBinaryOperatorResult
=================================================
The clang-analyzer-core.UndefinedBinaryOperatorResult check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-undefinedbinaryoperatorresult>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.uninitialized.ArraySubscript
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-arraysubscript
clang-analyzer-core.uninitialized.ArraySubscript
================================================
The clang-analyzer-core.uninitialized.ArraySubscript check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-arraysubscript>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.uninitialized.Assign
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-assign
clang-analyzer-core.uninitialized.Assign
========================================
The clang-analyzer-core.uninitialized.Assign check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-assign>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.uninitialized.Branch
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-branch
clang-analyzer-core.uninitialized.Branch
========================================
The clang-analyzer-core.uninitialized.Branch check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-branch>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.uninitialized.CapturedBlockVariable
clang-analyzer-core.uninitialized.CapturedBlockVariable
=======================================================
Check for blocks that capture uninitialized values
.. title:: clang-tidy - clang-analyzer-core.uninitialized.UndefReturn
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-undefreturn
clang-analyzer-core.uninitialized.UndefReturn
=============================================
The clang-analyzer-core.uninitialized.UndefReturn check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-uninitialized-undefreturn>`_
for more information.
.. title:: clang-tidy - clang-analyzer-core.VLASize
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#core-vlasize
clang-analyzer-core.VLASize
===========================
The clang-analyzer-core.VLASize check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#core-vlasize>`_
for more information.
.. title:: clang-tidy - clang-analyzer-cplusplus.InnerPointer
clang-analyzer-cplusplus.InnerPointer
=====================================
Check for inner pointers of C++ containers used after re/deallocation
.. title:: clang-tidy - clang-analyzer-cplusplus.Move
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-move
clang-analyzer-cplusplus.Move
=============================
The clang-analyzer-cplusplus.Move check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-move>`_
for more information.
.. title:: clang-tidy - clang-analyzer-cplusplus.NewDelete
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-newdelete
clang-analyzer-cplusplus.NewDelete
==================================
The clang-analyzer-cplusplus.NewDelete check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-newdelete>`_
for more information.
.. title:: clang-tidy - clang-analyzer-cplusplus.NewDeleteLeaks
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-newdeleteleaks
clang-analyzer-cplusplus.NewDeleteLeaks
=======================================
The clang-analyzer-cplusplus.NewDeleteLeaks check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#cplusplus-newdeleteleaks>`_
for more information.
.. title:: clang-tidy - clang-analyzer-deadcode.DeadStores
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#deadcode-deadstores
clang-analyzer-deadcode.DeadStores
==================================
The clang-analyzer-deadcode.DeadStores check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#deadcode-deadstores>`_
for more information.
.. title:: clang-tidy - clang-analyzer-nullability.NullableDereferenced
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullabledereferenced
clang-analyzer-nullability.NullableDereferenced
===============================================
The clang-analyzer-nullability.NullableDereferenced check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullabledereferenced>`_
for more information.
.. title:: clang-tidy - clang-analyzer-nullability.NullablePassedToNonnull
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullablepassedtononnull
clang-analyzer-nullability.NullablePassedToNonnull
==================================================
The clang-analyzer-nullability.NullablePassedToNonnull check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullablepassedtononnull>`_
for more information.
.. title:: clang-tidy - clang-analyzer-nullability.NullableReturnedFromNonnull
clang-analyzer-nullability.NullableReturnedFromNonnull
======================================================
Warns when a nullable pointer is returned from a function that has _Nonnull return type.
.. title:: clang-tidy - clang-analyzer-nullability.NullPassedToNonnull
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullpassedtononnull
clang-analyzer-nullability.NullPassedToNonnull
==============================================
The clang-analyzer-nullability.NullPassedToNonnull check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullpassedtononnull>`_
for more information.
.. title:: clang-tidy - clang-analyzer-nullability.NullReturnedFromNonnull
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullreturnedfromnonnull
clang-analyzer-nullability.NullReturnedFromNonnull
==================================================
The clang-analyzer-nullability.NullReturnedFromNonnull check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#nullability-nullreturnedfromnonnull>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.cplusplus.UninitializedObject
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-cplusplus-uninitializedobject
clang-analyzer-optin.cplusplus.UninitializedObject
==================================================
The clang-analyzer-optin.cplusplus.UninitializedObject check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-cplusplus-uninitializedobject>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.cplusplus.VirtualCall
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-cplusplus-virtualcall
clang-analyzer-optin.cplusplus.VirtualCall
==========================================
The clang-analyzer-optin.cplusplus.VirtualCall check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-cplusplus-virtualcall>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.mpi.MPI-Checker
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-mpi-mpi-checker
clang-analyzer-optin.mpi.MPI-Checker
====================================
The clang-analyzer-optin.mpi.MPI-Checker check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-mpi-mpi-checker>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-osx-cocoa-localizability-emptylocalizationcontextchecker
clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker
=============================================================================
The clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-osx-cocoa-localizability-emptylocalizationcontextchecker>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#optin-osx-cocoa-localizability-nonlocalizedstringchecker
clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker
=======================================================================
The clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#optin-osx-cocoa-localizability-nonlocalizedstringchecker>`_
for more information.
.. title:: clang-tidy - clang-analyzer-optin.osx.OSObjectCStyleCast
clang-analyzer-optin.osx.OSObjectCStyleCast
===========================================
Checker for C-style casts of OSObjects
.. title:: clang-tidy - clang-analyzer-optin.performance.GCDAntipattern
clang-analyzer-optin.performance.GCDAntipattern
===============================================
Check for performance anti-patterns when using Grand Central Dispatch
.. title:: clang-tidy - clang-analyzer-optin.performance.Padding
clang-analyzer-optin.performance.Padding
========================================
Check for excessively padded structs.
.. title:: clang-tidy - clang-analyzer-optin.portability.UnixAPI
clang-analyzer-optin.portability.UnixAPI
========================================
Finds implementation-defined behavior in UNIX/Posix functions
.. title:: clang-tidy - clang-analyzer-osx.API
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-api
clang-analyzer-osx.API
======================
The clang-analyzer-osx.API check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-api>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.AtSync
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-atsync
clang-analyzer-osx.cocoa.AtSync
===============================
The clang-analyzer-osx.cocoa.AtSync check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-atsync>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.AutoreleaseWrite
clang-analyzer-osx.cocoa.AutoreleaseWrite
=========================================
Warn about potentially crashing writes to autoreleasing objects from different autoreleasing pools in Objective-C
.. title:: clang-tidy - clang-analyzer-osx.cocoa.ClassRelease
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-classrelease
clang-analyzer-osx.cocoa.ClassRelease
=====================================
The clang-analyzer-osx.cocoa.ClassRelease check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-classrelease>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.Dealloc
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-dealloc
clang-analyzer-osx.cocoa.Dealloc
================================
The clang-analyzer-osx.cocoa.Dealloc check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-dealloc>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.IncompatibleMethodTypes
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-incompatiblemethodtypes
clang-analyzer-osx.cocoa.IncompatibleMethodTypes
================================================
The clang-analyzer-osx.cocoa.IncompatibleMethodTypes check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-incompatiblemethodtypes>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.Loops
clang-analyzer-osx.cocoa.Loops
==============================
Improved modeling of loops using Cocoa collection types
.. title:: clang-tidy - clang-analyzer-osx.cocoa.MissingSuperCall
clang-analyzer-osx.cocoa.MissingSuperCall
=========================================
Warn about Objective-C methods that lack a necessary call to super
.. title:: clang-tidy - clang-analyzer-osx.cocoa.NilArg
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nilarg
clang-analyzer-osx.cocoa.NilArg
===============================
The clang-analyzer-osx.cocoa.NilArg check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nilarg>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.NonNilReturnValue
clang-analyzer-osx.cocoa.NonNilReturnValue
==========================================
Model the APIs that are guaranteed to return a non-nil value
.. title:: clang-tidy - clang-analyzer-osx.cocoa.NSAutoreleasePool
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nsautoreleasepool
clang-analyzer-osx.cocoa.NSAutoreleasePool
==========================================
The clang-analyzer-osx.cocoa.NSAutoreleasePool check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nsautoreleasepool>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.NSError
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nserror
clang-analyzer-osx.cocoa.NSError
================================
The clang-analyzer-osx.cocoa.NSError check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-nserror>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.ObjCGenerics
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-objcgenerics
clang-analyzer-osx.cocoa.ObjCGenerics
=====================================
The clang-analyzer-osx.cocoa.ObjCGenerics check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-objcgenerics>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.RetainCount
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-retaincount
clang-analyzer-osx.cocoa.RetainCount
====================================
The clang-analyzer-osx.cocoa.RetainCount check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-retaincount>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak
clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak
===============================================
Check for leaked memory in autorelease pools that will never be drained
.. title:: clang-tidy - clang-analyzer-osx.cocoa.SelfInit
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-selfinit
clang-analyzer-osx.cocoa.SelfInit
=================================
The clang-analyzer-osx.cocoa.SelfInit check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-selfinit>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.SuperDealloc
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-superdealloc
clang-analyzer-osx.cocoa.SuperDealloc
=====================================
The clang-analyzer-osx.cocoa.SuperDealloc check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-superdealloc>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.UnusedIvars
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-unusedivars
clang-analyzer-osx.cocoa.UnusedIvars
====================================
The clang-analyzer-osx.cocoa.UnusedIvars check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-unusedivars>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.cocoa.VariadicMethodTypes
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-variadicmethodtypes
clang-analyzer-osx.cocoa.VariadicMethodTypes
============================================
The clang-analyzer-osx.cocoa.VariadicMethodTypes check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-cocoa-variadicmethodtypes>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.CFError
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cferror
clang-analyzer-osx.coreFoundation.CFError
=========================================
The clang-analyzer-osx.coreFoundation.CFError check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cferror>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.CFNumber
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cfnumber
clang-analyzer-osx.coreFoundation.CFNumber
==========================================
The clang-analyzer-osx.coreFoundation.CFNumber check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cfnumber>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.CFRetainRelease
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cfretainrelease
clang-analyzer-osx.coreFoundation.CFRetainRelease
=================================================
The clang-analyzer-osx.coreFoundation.CFRetainRelease check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-cfretainrelease>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.containers.OutOfBounds
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-containers-outofbounds
clang-analyzer-osx.coreFoundation.containers.OutOfBounds
========================================================
The clang-analyzer-osx.coreFoundation.containers.OutOfBounds check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-containers-outofbounds>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.coreFoundation.containers.PointerSizedValues
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-containers-pointersizedvalues
clang-analyzer-osx.coreFoundation.containers.PointerSizedValues
===============================================================
The clang-analyzer-osx.coreFoundation.containers.PointerSizedValues check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-corefoundation-containers-pointersizedvalues>`_
for more information.
.. title:: clang-tidy - clang-analyzer-osx.MIG
clang-analyzer-osx.MIG
======================
Find violations of the Mach Interface Generator calling convention
.. title:: clang-tidy - clang-analyzer-osx.NumberObjectConversion
clang-analyzer-osx.NumberObjectConversion
=========================================
Check for erroneous conversions of objects representing numbers into numbers
.. title:: clang-tidy - clang-analyzer-osx.ObjCProperty
clang-analyzer-osx.ObjCProperty
===============================
Check for proper uses of Objective-C properties
.. title:: clang-tidy - clang-analyzer-osx.OSObjectRetainCount
clang-analyzer-osx.OSObjectRetainCount
======================================
Check for leaks and improper reference count management for OSObject
.. title:: clang-tidy - clang-analyzer-osx.SecKeychainAPI
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#osx-seckeychainapi
clang-analyzer-osx.SecKeychainAPI
=================================
The clang-analyzer-osx.SecKeychainAPI check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#osx-seckeychainapi>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.FloatLoopCounter
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-floatloopcounter
clang-analyzer-security.FloatLoopCounter
========================================
The clang-analyzer-security.FloatLoopCounter check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-floatloopcounter>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.bcmp
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bcmp
clang-analyzer-security.insecureAPI.bcmp
========================================
The clang-analyzer-security.insecureAPI.bcmp check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bcmp>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.bcopy
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bcopy
clang-analyzer-security.insecureAPI.bcopy
=========================================
The clang-analyzer-security.insecureAPI.bcopy check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bcopy>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.bzero
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bzero
clang-analyzer-security.insecureAPI.bzero
=========================================
The clang-analyzer-security.insecureAPI.bzero check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-bzero>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-deprecatedorunsafebufferhandling
clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling
====================================================================
The clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-deprecatedorunsafebufferhandling>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.getpw
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-getpw
clang-analyzer-security.insecureAPI.getpw
=========================================
The clang-analyzer-security.insecureAPI.getpw check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-getpw>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.gets
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-gets
clang-analyzer-security.insecureAPI.gets
========================================
The clang-analyzer-security.insecureAPI.gets check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-gets>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.mkstemp
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-mkstemp
clang-analyzer-security.insecureAPI.mkstemp
===========================================
The clang-analyzer-security.insecureAPI.mkstemp check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-mkstemp>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.mktemp
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-mktemp
clang-analyzer-security.insecureAPI.mktemp
==========================================
The clang-analyzer-security.insecureAPI.mktemp check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-mktemp>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.rand
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-rand
clang-analyzer-security.insecureAPI.rand
========================================
The clang-analyzer-security.insecureAPI.rand check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-rand>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.strcpy
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-strcpy
clang-analyzer-security.insecureAPI.strcpy
==========================================
The clang-analyzer-security.insecureAPI.strcpy check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-strcpy>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.UncheckedReturn
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-uncheckedreturn
clang-analyzer-security.insecureAPI.UncheckedReturn
===================================================
The clang-analyzer-security.insecureAPI.UncheckedReturn check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-uncheckedreturn>`_
for more information.
.. title:: clang-tidy - clang-analyzer-security.insecureAPI.vfork
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-vfork
clang-analyzer-security.insecureAPI.vfork
=========================================
The clang-analyzer-security.insecureAPI.vfork check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#security-insecureapi-vfork>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.API
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-api
clang-analyzer-unix.API
=======================
The clang-analyzer-unix.API check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-api>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.cstring.BadSizeArg
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-cstring-badsizearg
clang-analyzer-unix.cstring.BadSizeArg
======================================
The clang-analyzer-unix.cstring.BadSizeArg check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-cstring-badsizearg>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.cstring.NullArg
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-cstring-nullarg
clang-analyzer-unix.cstring.NullArg
===================================
The clang-analyzer-unix.cstring.NullArg check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-cstring-nullarg>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.Malloc
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-malloc
clang-analyzer-unix.Malloc
==========================
The clang-analyzer-unix.Malloc check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-malloc>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.MallocSizeof
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-mallocsizeof
clang-analyzer-unix.MallocSizeof
================================
The clang-analyzer-unix.MallocSizeof check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-mallocsizeof>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.MismatchedDeallocator
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-mismatcheddeallocator
clang-analyzer-unix.MismatchedDeallocator
=========================================
The clang-analyzer-unix.MismatchedDeallocator check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-mismatcheddeallocator>`_
for more information.
.. title:: clang-tidy - clang-analyzer-unix.Vfork
.. meta::
:http-equiv=refresh: 5;URL=https://clang.llvm.org/docs/analyzer/checkers.html#unix-vfork
clang-analyzer-unix.Vfork
=========================
The clang-analyzer-unix.Vfork check is an alias, please see
`Clang Static Analyzer Available Checkers <https://clang.llvm.org/docs/analyzer/checkers.html#unix-vfork>`_
for more information.
.. title:: clang-tidy - clang-analyzer-valist.CopyToSelf
clang-analyzer-valist.CopyToSelf
================================
Check for va_lists which are copied onto itself.
.. title:: clang-tidy - clang-analyzer-valist.Uninitialized
clang-analyzer-valist.Uninitialized
===================================
Check for usages of uninitialized (or already released) va_lists.
.. title:: clang-tidy - clang-analyzer-valist.Unterminated
clang-analyzer-valist.Unterminated
==================================
Check for va_lists which are not released by a va_end call.
.. title:: clang-tidy - concurrency-mt-unsafe
concurrency-mt-unsafe
=====================
Checks for some thread-unsafe functions against a black list of
known-to-be-unsafe functions. Usually they access static variables without
synchronization (e.g. gmtime(3)) or utilize signals in a racy way.
The set of functions to check is specified with the `FunctionSet` option.
Note that using some thread-unsafe functions may be still valid in
concurrent programming if only a single thread is used (e.g. setenv(3)),
however, some functions may track a state in global variables which
would be clobbered by subsequent (non-parallel, but concurrent) calls to
a related function. E.g. the following code suffers from unprotected
accesses to a global state:
.. code-block:: c++
// getnetent(3) maintains global state with DB connection, etc.
// If a concurrent green thread calls getnetent(3), the global state is corrupted.
netent = getnetent();
yield();
netent = getnetent();
Examples:
.. code-block:: c++
tm = gmtime(timep); // uses a global buffer
sleep(1); // implementation may use SIGALRM
.. option:: FunctionSet
Specifies which functions in libc should be considered thread-safe,
possible values are `posix`, `glibc`, or `any`.
`posix` means POSIX defined thread-unsafe functions. POSIX.1-2001
in "2.9.1 Thread-Safety" defines that all functions specified in the
standard are thread-safe except a predefined list of thread-unsafe
functions.
Glibc defines some of them as thread-safe (e.g. dirname(3)), but adds
non-POSIX thread-unsafe ones (e.g. getopt_long(3)). Glibc's list is
compiled from GNU web documentation with a search for MT-Safe tag:
https://www.gnu.org/software/libc/manual/html_node/POSIX-Safety-Concepts.html
If you want to identify thread-unsafe API for at least one libc or
unsure which libc will be used, use `any` (default).
.. title:: clang-tidy - concurrency-thread-canceltype-asynchronous
concurrency-thread-canceltype-asynchronous
==========================================
Finds ``pthread_setcanceltype`` function calls where a thread's cancellation
type is set to asynchronous. Asynchronous cancellation type
(``PTHREAD_CANCEL_ASYNCHRONOUS``) is generally unsafe, use type
``PTHREAD_CANCEL_DEFERRED`` instead which is the default. Even with deferred
cancellation, a cancellation point in an asynchronous signal handler may still
be acted upon and the effect is as if it was an asynchronous cancellation.
.. code-block: c++
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);
This check corresponds to the CERT C Coding Standard rule
`POS47-C. Do not use threads that can be canceled asynchronously
<https://wiki.sei.cmu.edu/confluence/display/c/POS47-C.+Do+not+use+threads+that+can+be+canceled+asynchronously>`_.
.. title:: clang-tidy - cppcoreguidelines-avoid-c-arrays
.. meta::
:http-equiv=refresh: 5;URL=modernize-avoid-c-arrays.html
cppcoreguidelines-avoid-c-arrays
================================
The cppcoreguidelines-avoid-c-arrays check is an alias, please see
`modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-avoid-goto
cppcoreguidelines-avoid-goto
============================
The usage of ``goto`` for control flow is error prone and should be replaced
with looping constructs. Only forward jumps in nested loops are accepted.
This check implements `ES.76 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es76-avoid-goto>`_
from the CppCoreGuidelines and
`6.3.1 from High Integrity C++ <http://www.codingstandard.com/rule/6-3-1-ensure-that-the-labels-for-a-jump-statement-or-a-switch-condition-appear-later-in-the-same-or-an-enclosing-block/>`_.
For more information on why to avoid programming
with ``goto`` you can read the famous paper `A Case against the GO TO Statement. <https://www.cs.utexas.edu/users/EWD/ewd02xx/EWD215.PDF>`_.
The check diagnoses ``goto`` for backward jumps in every language mode. These
should be replaced with `C/C++` looping constructs.
.. code-block:: c++
// Bad, handwritten for loop.
int i = 0;
// Jump label for the loop
loop_start:
do_some_operation();
if (i < 100) {
++i;
goto loop_start;
}
// Better
for(int i = 0; i < 100; ++i)
do_some_operation();
Modern C++ needs ``goto`` only to jump out of nested loops.
.. code-block:: c++
for(int i = 0; i < 100; ++i) {
for(int j = 0; j < 100; ++j) {
if (i * j > 500)
goto early_exit;
}
}
early_exit:
some_operation();
All other uses of ``goto`` are diagnosed in `C++`.
.. title:: clang-tidy - cppcoreguidelines-avoid-magic-numbers
.. meta::
:http-equiv=refresh: 5;URL=readability-magic-numbers.html
cppcoreguidelines-avoid-magic-numbers
=====================================
The cppcoreguidelines-avoid-magic-numbers check is an alias, please see
`readability-magic-numbers <readability-magic-numbers.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-avoid-non-const-global-variables
cppcoreguidelines-avoid-non-const-global-variables
==================================================
Finds non-const global variables as described in `I.2 of C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-global>`_ .
As `R.6 of C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rr-global>`_ is a duplicate of rule I.2 it also covers that rule.
.. code-block:: c++
char a; // Warns!
const char b = 0;
namespace some_namespace
{
char c; // Warns!
const char d = 0;
}
char * c_ptr1 = &some_namespace::c; // Warns!
char *const c_const_ptr = &some_namespace::c; // Warns!
char & c_reference = some_namespace::c; // Warns!
class Foo // No Warnings inside Foo, only namespace scope is covered
{
public:
char e = 0;
const char f = 0;
protected:
char g = 0;
private:
char h = 0;
};
Variables: ``a``, ``c``, ``c_ptr1``, ``c_ptr2``, ``c_const_ptr`` and
``c_reference``, will all generate warnings since they are either:
a globally accessible variable and non-const, a pointer or reference providing
global access to non-const data or both.
.. title:: clang-tidy - cppcoreguidelines-c-copy-assignment-signature
.. meta::
:http-equiv=refresh: 5;URL=misc-unconventional-assign-operator.html
cppcoreguidelines-c-copy-assignment-signature
=============================================
The cppcoreguidelines-c-copy-assignment-signature check is an alias, please see
`misc-unconventional-assign-operator <misc-unconventional-assign-operator.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-explicit-virtual-functions
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-override.html
cppcoreguidelines-explicit-virtual-functions
============================================
The cppcoreguidelines-explicit-virtual-functions check is an alias, please see
`modernize-use-override <modernize-use-override.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-init-variables
cppcoreguidelines-init-variables
================================
Checks whether there are local variables that are declared without an initial
value. These may lead to unexpected behaviour if there is a code path that reads
the variable before assigning to it.
Only integers, booleans, floats, doubles and pointers are checked. The fix
option initializes all detected values with the value of zero. An exception is
float and double types, which are initialized to NaN.
As an example a function that looks like this:
.. code-block:: c++
void function() {
int x;
char *txt;
double d;
// Rest of the function.
}
Would be rewritten to look like this:
.. code-block:: c++
#include <math.h>
void function() {
int x = 0;
char *txt = nullptr;
double d = NAN;
// Rest of the function.
}
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: MathHeader
A string specifying the header to include to get the definition of `NAN`.
Default is `<math.h>`.
.. title:: clang-tidy - cppcoreguidelines-interfaces-global-init
cppcoreguidelines-interfaces-global-init
========================================
This check flags initializers of globals that access extern objects,
and therefore can lead to order-of-initialization problems.
This rule is part of the "Interfaces" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-global-init
Note that currently this does not flag calls to non-constexpr functions, and
therefore globals could still be accessed from functions themselves.
.. title:: clang-tidy - cppcoreguidelines-macro-usage
cppcoreguidelines-macro-usage
=============================
Finds macro usage that is considered problematic because better language
constructs exist for the task.
The relevant sections in the C++ Core Guidelines are
`Enum.1 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#enum1-prefer-enumerations-over-macros>`_,
`ES.30 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es30-dont-use-macros-for-program-text-manipulation>`_,
`ES.31 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es31-dont-use-macros-for-constants-or-functions>`_ and
`ES.33 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es33-if-you-must-use-macros-give-them-unique-names>`_.
Options
-------
.. option:: AllowedRegexp
A regular expression to filter allowed macros. For example
`DEBUG*|LIBTORRENT*|TORRENT*|UNI*` could be applied to filter `libtorrent`.
Default value is `^DEBUG_*`.
.. option:: CheckCapsOnly
Boolean flag to warn on all macros except those with CAPS_ONLY names.
This option is intended to ease introduction of this check into older
code bases. Default value is `false`.
.. option:: IgnoreCommandLineMacros
Boolean flag to toggle ignoring command-line-defined macros.
Default value is `true`.
.. title:: clang-tidy - cppcoreguidelines-narrowing-conversions
cppcoreguidelines-narrowing-conversions
=======================================
Checks for silent narrowing conversions, e.g: ``int i = 0; i += 0.1;``. While
the issue is obvious in this former example, it might not be so in the
following: ``void MyClass::f(double d) { int_member_ += d; }``.
This rule is part of the "Expressions and statements" profile of the C++ Core
Guidelines, corresponding to rule ES.46. See
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es46-avoid-lossy-narrowing-truncating-arithmetic-conversions.
We enforce only part of the guideline, more specifically, we flag narrowing conversions from:
- an integer to a narrower integer (e.g. ``char`` to ``unsigned char``)
if WarnOnIntegerNarrowingConversion Option is set,
- an integer to a narrower floating-point (e.g. ``uint64_t`` to ``float``),
- a floating-point to an integer (e.g. ``double`` to ``int``),
- a floating-point to a narrower floating-point (e.g. ``double`` to ``float``)
if WarnOnFloatingPointNarrowingConversion Option is set.
This check will flag:
- All narrowing conversions that are not marked by an explicit cast (c-style or
``static_cast``). For example: ``int i = 0; i += 0.1;``,
``void f(int); f(0.1);``,
- All applications of binary operators with a narrowing conversions.
For example: ``int i; i+= 0.1;``.
Options
-------
.. option:: WarnOnIntegerNarrowingConversion
When `true`, the check will warn on narrowing integer conversion
(e.g. ``int`` to ``size_t``). `true` by default.
.. option:: WarnOnFloatingPointNarrowingConversion
When `true`, the check will warn on narrowing floating point conversion
(e.g. ``double`` to ``float``). `true` by default.
.. option:: WarnWithinTemplateInstantiation
When `true`, the check will warn on narrowing conversions within template
instantations. `false` by default.
.. option:: WarnOnEquivalentBitWidth
When `true`, the check will warn on narrowing conversions that arise from
casting between types of equivalent bit width. (e.g.
`int n = uint(0);` or `long long n = double(0);`) `true` by default.
.. option:: IgnoreConversionFromTypes
Narrowing conversions from any type in this semicolon-separated list will be
ignored. This may be useful to weed out commonly occurring, but less commonly
problematic assignments such as `int n = std::vector<char>().size();` or
`int n = std::difference(it1, it2);`. The default list is empty, but one
suggested list for a legacy codebase would be
`size_t;ptrdiff_t;size_type;difference_type`.
.. option:: PedanticMode
When `true`, the check will warn on assigning a floating point constant
to an integer value even if the floating point value is exactly
representable in the destination type (e.g. ``int i = 1.0;``).
`false` by default.
FAQ
---
- What does "narrowing conversion from 'int' to 'float'" mean?
An IEEE754 Floating Point number can represent all integer values in the range
[-2^PrecisionBits, 2^PrecisionBits] where PrecisionBits is the number of bits in
the mantissa.
For ``float`` this would be [-2^23, 2^23], where ``int`` can represent values in
the range [-2^31, 2^31-1].
- What does "implementation-defined" mean?
You may have encountered messages like "narrowing conversion from 'unsigned int'
to signed type 'int' is implementation-defined".
The C/C++ standard does not mandate two’s complement for signed integers, and so
the compiler is free to define what the semantics are for converting an unsigned
integer to signed integer. Clang's implementation uses the two’s complement
format.
.. title:: clang-tidy - cppcoreguidelines-no-malloc
cppcoreguidelines-no-malloc
===========================
This check handles C-Style memory management using ``malloc()``, ``realloc()``,
``calloc()`` and ``free()``. It warns about its use and tries to suggest the use
of an appropriate RAII object.
Furthermore, it can be configured to check against a user-specified list of functions
that are used for memory management (e.g. ``posix_memalign()``).
See `C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rr-mallocfree>`_.
There is no attempt made to provide fix-it hints, since manual resource
management isn't easily transformed automatically into RAII.
.. code-block:: c++
// Warns each of the following lines.
// Containers like std::vector or std::string should be used.
char* some_string = (char*) malloc(sizeof(char) * 20);
char* some_string = (char*) realloc(sizeof(char) * 30);
free(some_string);
int* int_array = (int*) calloc(30, sizeof(int));
// Rather use a smartpointer or stack variable.
struct some_struct* s = (struct some_struct*) malloc(sizeof(struct some_struct));
Options
-------
.. option:: Allocations
Semicolon-separated list of fully qualified names of memory allocation functions.
Defaults to ``::malloc;::calloc``.
.. option:: Deallocations
Semicolon-separated list of fully qualified names of memory allocation functions.
Defaults to ``::free``.
.. option:: Reallocations
Semicolon-separated list of fully qualified names of memory allocation functions.
Defaults to ``::realloc``.
.. title:: clang-tidy - cppcoreguidelines-non-private-member-variables-in-classes
.. meta::
:http-equiv=refresh: 5;URL=misc-non-private-member-variables-in-classes.html
cppcoreguidelines-non-private-member-variables-in-classes
=========================================================
The cppcoreguidelines-non-private-member-variables-in-classes check is an alias,
please see
`misc-non-private-member-variables-in-classes <misc-non-private-member-variables-in-classes.html>`_
for more information.
.. title:: clang-tidy - cppcoreguidelines-owning-memory
cppcoreguidelines-owning-memory
===============================
This check implements the type-based semantics of ``gsl::owner<T*>``, which allows
static analysis on code, that uses raw pointers to handle resources like
dynamic memory, but won't introduce RAII concepts.
The relevant sections in the `C++ Core Guidelines <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md>`_ are I.11, C.33, R.3 and GSL.Views
The definition of a ``gsl::owner<T*>`` is straight forward
.. code-block:: c++
namespace gsl { template <typename T> owner = T; }
It is therefore simple to introduce the owner even without using an implementation of
the `Guideline Support Library <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#gsl-guideline-support-library>`_.
All checks are purely type based and not (yet) flow sensitive.
The following examples will demonstrate the correct and incorrect initializations
of owners, assignment is handled the same way. Note that both ``new`` and
``malloc()``-like resource functions are considered to produce resources.
.. code-block:: c++
// Creating an owner with factory functions is checked.
gsl::owner<int*> function_that_returns_owner() { return gsl::owner<int*>(new int(42)); }
// Dynamic memory must be assigned to an owner
int* Something = new int(42); // BAD, will be caught
gsl::owner<int*> Owner = new int(42); // Good
gsl::owner<int*> Owner = new int[42]; // Good as well
// Returned owner must be assigned to an owner
int* Something = function_that_returns_owner(); // Bad, factory function
gsl::owner<int*> Owner = function_that_returns_owner(); // Good, result lands in owner
// Something not a resource or owner should not be assigned to owners
int Stack = 42;
gsl::owner<int*> Owned = &Stack; // Bad, not a resource assigned
In the case of dynamic memory as resource, only ``gsl::owner<T*>`` variables are allowed
to be deleted.
.. code-block:: c++
// Example Bad, non-owner as resource handle, will be caught.
int* NonOwner = new int(42); // First warning here, since new must land in an owner
delete NonOwner; // Second warning here, since only owners are allowed to be deleted
// Example Good, Ownership correctly stated
gsl::owner<int*> Owner = new int(42); // Good
delete Owner; // Good as well, statically enforced, that only owners get deleted
The check will furthermore ensure, that functions, that expect a ``gsl::owner<T*>`` as
argument get called with either a ``gsl::owner<T*>`` or a newly created resource.
.. code-block:: c++
void expects_owner(gsl::owner<int*> o) { delete o; }
// Bad Code
int NonOwner = 42;
expects_owner(&NonOwner); // Bad, will get caught
// Good Code
gsl::owner<int*> Owner = new int(42);
expects_owner(Owner); // Good
expects_owner(new int(42)); // Good as well, recognized created resource
// Port legacy code for better resource-safety
gsl::owner<FILE*> File = fopen("my_file.txt", "rw+");
FILE* BadFile = fopen("another_file.txt", "w"); // Bad, warned
// ... use the file
fclose(File); // Ok, File is annotated as 'owner<>'
fclose(BadFile); // BadFile is not an 'owner<>', will be warned
Options
-------
.. option:: LegacyResourceProducers
Semicolon-separated list of fully qualified names of legacy functions that create
resources but cannot introduce ``gsl::owner<>``.
Defaults to ``::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile``.
.. option:: LegacyResourceConsumers
Semicolon-separated list of fully qualified names of legacy functions expecting
resource owners as pointer arguments but cannot introduce ``gsl::owner<>``.
Defaults to ``::free;::realloc;::freopen;::fclose``.
Limitations
-----------
Using ``gsl::owner<T*>`` in a typedef or alias is not handled correctly.
.. code-block:: c++
using heap_int = gsl::owner<int*>;
heap_int allocated = new int(42); // False positive!
The ``gsl::owner<T*>`` is declared as a templated type alias.
In template functions and classes, like in the example below, the information
of the type aliases gets lost. Therefore using ``gsl::owner<T*>`` in a heavy templated
code base might lead to false positives.
Known code constructs that do not get diagnosed correctly are:
- ``std::exchange``
- ``std::vector<gsl::owner<T*>>``
.. code-block:: c++
// This template function works as expected. Type information doesn't get lost.
template <typename T>
void delete_owner(gsl::owner<T*> owned_object) {
delete owned_object; // Everything alright
}
gsl::owner<int*> function_that_returns_owner() { return gsl::owner<int*>(new int(42)); }
// Type deduction does not work for auto variables.
// This is caught by the check and will be noted accordingly.
auto OwnedObject = function_that_returns_owner(); // Type of OwnedObject will be int*
// Problematic function template that looses the typeinformation on owner
template <typename T>
void bad_template_function(T some_object) {
// This line will trigger the warning, that a non-owner is assigned to an owner
gsl::owner<T*> new_owner = some_object;
}
// Calling the function with an owner still yields a false positive.
bad_template_function(gsl::owner<int*>(new int(42)));
// The same issue occurs with templated classes like the following.
template <typename T>
class OwnedValue {
public:
const T getValue() const { return _val; }
private:
T _val;
};
// Code, that yields a false positive.
OwnedValue<gsl::owner<int*>> Owner(new int(42)); // Type deduction yield T -> int *
// False positive, getValue returns int* and not gsl::owner<int*>
gsl::owner<int*> OwnedInt = Owner.getValue();
Another limitation of the current implementation is only the type based checking.
Suppose you have code like the following:
.. code-block:: c++
// Two owners with assigned resources
gsl::owner<int*> Owner1 = new int(42);
gsl::owner<int*> Owner2 = new int(42);
Owner2 = Owner1; // Conceptual Leak of initial resource of Owner2!
Owner1 = nullptr;
The semantic of a ``gsl::owner<T*>`` is mostly like a ``std::unique_ptr<T>``, therefore
assignment of two ``gsl::owner<T*>`` is considered a move, which requires that the
resource ``Owner2`` must have been released before the assignment.
This kind of condition could be caught in later improvements of this check with
flowsensitive analysis. Currently, the `Clang Static Analyzer` catches this bug
for dynamic memory, but not for general types of resources.
.. title:: clang-tidy - cppcoreguidelines-prefer-member-initializer
cppcoreguidelines-prefer-member-initializer
===========================================
Finds member initializations in the constructor body which can be converted
into member initializers of the constructor instead. This not only improves
the readability of the code but also positively affects its performance.
Class-member assignments inside a control statement or following the first
control statement are ignored.
This check implements `C.49 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c49-prefer-initialization-to-assignment-in-constructors>`_ from the CppCoreGuidelines.
If the language version is `C++ 11` or above, the constructor is the default
constructor of the class, the field is not a bitfield (only in case of earlier
language version than `C++ 20`), furthermore the assigned value is a literal,
negated literal or ``enum`` constant then the preferred place of the
initialization is at the class member declaration.
This latter rule is `C.48 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c48-prefer-in-class-initializers-to-member-initializers-in-constructors-for-constant-initializers>`_ from CppCoreGuidelines.
Please note, that this check does not enforce this latter rule for
initializations already implemented as member initializers. For that purpose
see check `modernize-use-default-member-init <modernize-use-default-member-init.html>`_.
Example 1
---------
.. code-block:: c++
class C {
int n;
int m;
public:
C() {
n = 1; // Literal in default constructor
if (dice())
return;
m = 1;
}
};
Here ``n`` can be initialized using a default member initializer, unlike
``m``, as ``m``'s initialization follows a control statement (``if``):
.. code-block:: c++
class C {
int n{1};
int m;
public:
C() {
if (dice())
return;
m = 1;
}
Example 2
---------
.. code-block:: c++
class C {
int n;
int m;
public:
C(int nn, int mm) {
n = nn; // Neither default constructor nor literal
if (dice())
return;
m = mm;
}
};
Here ``n`` can be initialized in the constructor initialization list, unlike
``m``, as ``m``'s initialization follows a control statement (``if``):
.. code-block:: c++
C(int nn, int mm) : n(nn) {
if (dice())
return;
m = mm;
}
.. option:: UseAssignment
If this option is set to `true` (default is `false`), the check will initialize
members with an assignment. In this case the fix of the first example looks
like this:
.. code-block:: c++
class C {
int n = 1;
int m;
public:
C() {
if (dice())
return;
m = 1;
}
};
.. title:: clang-tidy - cppcoreguidelines-pro-bounds-array-to-pointer-decay
cppcoreguidelines-pro-bounds-array-to-pointer-decay
===================================================
This check flags all array to pointer decays.
Pointers should not be used as arrays. ``span<T>`` is a bounds-checked, safe
alternative to using pointers to access arrays.
This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-decay.
.. title:: clang-tidy - cppcoreguidelines-pro-bounds-constant-array-index
cppcoreguidelines-pro-bounds-constant-array-index
=================================================
This check flags all array subscript expressions on static arrays and
``std::arrays`` that either do not have a constant integer expression index or
are out of bounds (for ``std::array``). For out-of-bounds checking of static
arrays, see the `-Warray-bounds` Clang diagnostic.
This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-arrayindex.
Options
-------
.. option:: GslHeader
The check can generate fixes after this option has been set to the name of
the include file that contains ``gsl::at()``, e.g. `"gsl/gsl.h"`.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. title:: clang-tidy - cppcoreguidelines-pro-bounds-pointer-arithmetic
cppcoreguidelines-pro-bounds-pointer-arithmetic
===============================================
This check flags all usage of pointer arithmetic, because it could lead to an
invalid pointer. Subtraction of two pointers is not flagged by this check.
Pointers should only refer to single objects, and pointer arithmetic is fragile
and easy to get wrong. ``span<T>`` is a bounds-checked, safe type for accessing
arrays of data.
This rule is part of the "Bounds safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-bounds-arithmetic.
.. title:: clang-tidy - cppcoreguidelines-pro-type-const-cast
cppcoreguidelines-pro-type-const-cast
=====================================
This check flags all uses of ``const_cast`` in C++ code.
Modifying a variable that was declared const is undefined behavior, even with
``const_cast``.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-constcast.
.. title:: clang-tidy - cppcoreguidelines-pro-type-cstyle-cast
cppcoreguidelines-pro-type-cstyle-cast
======================================
This check flags all use of C-style casts that perform a ``static_cast``
downcast, ``const_cast``, or ``reinterpret_cast``.
Use of these casts can violate type safety and cause the program to access a
variable that is actually of type X to be accessed as if it were of an unrelated
type Z. Note that a C-style ``(T)expression`` cast means to perform the first of
the following that is possible: a ``const_cast``, a ``static_cast``, a
``static_cast`` followed by a ``const_cast``, a ``reinterpret_cast``, or a
``reinterpret_cast`` followed by a ``const_cast``. This rule bans
``(T)expression`` only when used to perform an unsafe cast.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-cstylecast.
.. title:: clang-tidy - cppcoreguidelines-pro-type-member-init
cppcoreguidelines-pro-type-member-init
======================================
The check flags user-defined constructor definitions that do not
initialize all fields that would be left in an undefined state by
default construction, e.g. builtins, pointers and record types without
user-provided default constructors containing at least one such
type. If these fields aren't initialized, the constructor will leave
some of the memory in an undefined state.
For C++11 it suggests fixes to add in-class field initializers. For
older versions it inserts the field initializers into the constructor
initializer list. It will also initialize any direct base classes that
need to be zeroed in the constructor initializer list.
The check takes assignment of fields in the constructor body into
account but generates false positives for fields initialized in
methods invoked in the constructor body.
The check also flags variables with automatic storage duration that have record
types without a user-provided constructor and are not initialized. The suggested
fix is to zero initialize the variable via ``{}`` for C++11 and beyond or ``=
{}`` for older language versions.
Options
-------
.. option:: IgnoreArrays
If set to `true`, the check will not warn about array members that are not
zero-initialized during construction. For performance critical code, it may
be important to not initialize fixed-size array members. Default is `false`.
.. option:: UseAssignment
If set to `true`, the check will provide fix-its with literal initializers
\( ``int i = 0;`` \) instead of curly braces \( ``int i{};`` \).
This rule is part of the "Type safety" profile of the C++ Core
Guidelines, corresponding to rule Type.6. See
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-memberinit.
.. title:: clang-tidy - cppcoreguidelines-pro-type-reinterpret-cast
cppcoreguidelines-pro-type-reinterpret-cast
===========================================
This check flags all uses of ``reinterpret_cast`` in C++ code.
Use of these casts can violate type safety and cause the program to access a
variable that is actually of type ``X`` to be accessed as if it were of an
unrelated type ``Z``.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-reinterpretcast.
.. title:: clang-tidy - cppcoreguidelines-pro-type-static-cast-downcast
cppcoreguidelines-pro-type-static-cast-downcast
===============================================
This check flags all usages of ``static_cast``, where a base class is casted to
a derived class. In those cases, a fix-it is provided to convert the cast to a
``dynamic_cast``.
Use of these casts can violate type safety and cause the program to access a
variable that is actually of type ``X`` to be accessed as if it were of an
unrelated type ``Z``.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-downcast.
.. title:: clang-tidy - cppcoreguidelines-pro-type-union-access
cppcoreguidelines-pro-type-union-access
=======================================
This check flags all access to members of unions. Passing unions as a whole is
not flagged.
Reading from a union member assumes that member was the last one written, and
writing to a union member assumes another member with a nontrivial destructor
had its destructor called. This is fragile because it cannot generally be
enforced to be safe in the language and so relies on programmer discipline to
get it right.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-unions.
.. title:: clang-tidy - cppcoreguidelines-pro-type-vararg
cppcoreguidelines-pro-type-vararg
=================================
This check flags all calls to c-style vararg functions and all use of
``va_arg``.
To allow for SFINAE use of vararg functions, a call is not flagged if a literal
0 is passed as the only vararg argument.
Passing to varargs assumes the correct type will be read. This is fragile
because it cannot generally be enforced to be safe in the language and so relies
on programmer discipline to get it right.
This rule is part of the "Type safety" profile of the C++ Core Guidelines, see
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Pro-type-varargs.
.. title:: clang-tidy - cppcoreguidelines-slicing
cppcoreguidelines-slicing
=========================
Flags slicing of member variables or vtable. Slicing happens when copying a
derived object into a base object: the members of the derived object (both
member variables and virtual member functions) will be discarded. This can be
misleading especially for member function slicing, for example:
.. code-block:: c++
struct B { int a; virtual int f(); };
struct D : B { int b; int f() override; };
void use(B b) { // Missing reference, intended?
b.f(); // Calls B::f.
}
D d;
use(d); // Slice.
See the relevant C++ Core Guidelines sections for details:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es63-dont-slice
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c145-access-polymorphic-objects-through-pointers-and-references
.. title:: clang-tidy - cppcoreguidelines-special-member-functions
cppcoreguidelines-special-member-functions
==========================================
The check finds classes where some but not all of the special member functions
are defined.
By default the compiler defines a copy constructor, copy assignment operator,
move constructor, move assignment operator and destructor. The default can be
suppressed by explicit user-definitions. The relationship between which
functions will be suppressed by definitions of other functions is complicated
and it is advised that all five are defaulted or explicitly defined.
Note that defining a function with ``= delete`` is considered to be a
definition.
This rule is part of the "Constructors, assignments, and destructors" profile of the C++ Core
Guidelines, corresponding to rule C.21. See
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all.
Options
-------
.. option:: AllowSoleDefaultDtor
When set to `true` (default is `false`), this check doesn't flag classes with a sole, explicitly
defaulted destructor. An example for such a class is:
.. code-block:: c++
struct A {
virtual ~A() = default;
};
.. option:: AllowMissingMoveFunctions
When set to `true` (default is `false`), this check doesn't flag classes which define no move
operations at all. It still flags classes which define only one of either
move constructor or move assignment operator. With this option enabled, the following class won't be flagged:
.. code-block:: c++
struct A {
A(const A&);
A& operator=(const A&);
~A();
};
.. option:: AllowMissingMoveFunctionsWhenCopyIsDeleted
When set to `true` (default is `false`), this check doesn't flag classes which define deleted copy
operations but don't define move operations. This flags is related to Google C++ Style Guide
https://google.github.io/styleguide/cppguide.html#Copyable_Movable_Types. With this option enabled, the
following class won't be flagged:
.. code-block:: c++
struct A {
A(const A&) = delete;
A& operator=(const A&) = delete;
~A();
};
.. title:: clang-tidy - darwin-avoid-spinlock
darwin-avoid-spinlock
=====================
Finds usages of ``OSSpinlock``, which is deprecated due to potential livelock
problems.
This check will detect following function invocations:
- ``OSSpinlockLock``
- ``OSSpinlockTry``
- ``OSSpinlockUnlock``
The corresponding information about the problem of ``OSSpinlock``: https://blog.postmates.com/why-spinlocks-are-bad-on-ios-b69fc5221058
.. title:: clang-tidy - darwin-dispatch-once-nonstatic
darwin-dispatch-once-nonstatic
==============================
Finds declarations of ``dispatch_once_t`` variables without static or global
storage. The behavior of using ``dispatch_once_t`` predicates with automatic or
dynamic storage is undefined by libdispatch, and should be avoided.
It is a common pattern to have functions initialize internal static or global
data once when the function runs, but programmers have been known to miss the
static on the ``dispatch_once_t`` predicate, leading to an uninitialized flag
value at the mercy of the stack.
Programmers have also been known to make ``dispatch_once_t`` variables be
members of structs or classes, with the intent to lazily perform some expensive
struct or class member initialization only once; however, this violates the
libdispatch requirements.
See the discussion section of
`Apple's dispatch_once documentation <https://developer.apple.com/documentation/dispatch/1447169-dispatch_once>`_
for more information.
.. title:: clang-tidy - fuchsia-default-arguments-calls
fuchsia-default-arguments-calls
===============================
Warns if a function or method is called with default arguments.
For example, given the declaration:
.. code-block:: c++
int foo(int value = 5) { return value; }
A function call expression that uses a default argument will be diagnosed.
Calling it without defaults will not cause a warning:
.. code-block:: c++
foo(); // warning
foo(0); // no warning
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-default-arguments-declarations
fuchsia-default-arguments-declarations
======================================
Warns if a function or method is declared with default parameters.
For example, the declaration:
.. code-block:: c++
int foo(int value = 5) { return value; }
will cause a warning.
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-header-anon-namespaces
.. meta::
:http-equiv=refresh: 5;URL=google-build-namespaces.html
fuchsia-header-anon-namespaces
==============================
The fuchsia-header-anon-namespaces check is an alias, please see
`google-build-namespace <google-build-namespaces.html>`_
for more information.
.. title:: clang-tidy - fuchsia-multiple-inheritance
fuchsia-multiple-inheritance
============================
Warns if a class inherits from multiple classes that are not pure virtual.
For example, declaring a class that inherits from multiple concrete classes is
disallowed:
.. code-block:: c++
class Base_A {
public:
virtual int foo() { return 0; }
};
class Base_B {
public:
virtual int bar() { return 0; }
};
// Warning
class Bad_Child1 : public Base_A, Base_B {};
A class that inherits from a pure virtual is allowed:
.. code-block:: c++
class Interface_A {
public:
virtual int foo() = 0;
};
class Interface_B {
public:
virtual int bar() = 0;
};
// No warning
class Good_Child1 : public Interface_A, Interface_B {
virtual int foo() override { return 0; }
virtual int bar() override { return 0; }
};
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-overloaded-operator
fuchsia-overloaded-operator
===========================
Warns if an operator is overloaded, except for the assignment (copy and move)
operators.
For example:
.. code-block:: c++
int operator+(int); // Warning
B &operator=(const B &Other); // No warning
B &operator=(B &&Other) // No warning
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-statically-constructed-objects
fuchsia-statically-constructed-objects
======================================
Warns if global, non-trivial objects with static storage are constructed, unless
the object is statically initialized with a ``constexpr`` constructor or has no
explicit constructor.
For example:
.. code-block:: c++
class A {};
class B {
public:
B(int Val) : Val(Val) {}
private:
int Val;
};
class C {
public:
C(int Val) : Val(Val) {}
constexpr C() : Val(0) {}
private:
int Val;
};
static A a; // No warning, as there is no explicit constructor
static C c(0); // No warning, as constructor is constexpr
static B b(0); // Warning, as constructor is not constexpr
static C c2(0, 1); // Warning, as constructor is not constexpr
static int i; // No warning, as it is trivial
extern int get_i();
static C(get_i()) // Warning, as the constructor is dynamically initialized
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-trailing-return
fuchsia-trailing-return
=======================
Functions that have trailing returns are disallowed, except for those using
``decltype`` specifiers and lambda with otherwise unutterable return types.
For example:
.. code-block:: c++
// No warning
int add_one(const int arg) { return arg; }
// Warning
auto get_add_one() -> int (*)(const int) {
return add_one;
}
Exceptions are made for lambdas and ``decltype`` specifiers:
.. code-block:: c++
// No warning
auto lambda = [](double x, double y) -> double {return x + y;};
// No warning
template <typename T1, typename T2>
auto fn(const T1 &lhs, const T2 &rhs) -> decltype(lhs + rhs) {
return lhs + rhs;
}
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - fuchsia-virtual-inheritance
fuchsia-virtual-inheritance
===========================
Warns if classes are defined with virtual inheritance.
For example, classes should not be defined with virtual inheritance:
.. code-block:: c++
class B : public virtual A {}; // warning
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
.. title:: clang-tidy - google-build-explicit-make-pair
google-build-explicit-make-pair
===============================
Check that ``make_pair``'s template arguments are deduced.
G++ 4.6 in C++11 mode fails badly if ``make_pair``'s template arguments are
specified explicitly, and such use isn't intended in any case.
Corresponding cpplint.py check name: `build/explicit_make_pair`.
.. title:: clang-tidy - google-build-namespaces
google-build-namespaces
=======================
`cert-dcl59-cpp` redirects here as an alias for this check.
`fuchsia-header-anon-namespaces` redirects here as an alias for this check.
Finds anonymous namespaces in headers.
https://google.github.io/styleguide/cppguide.html#Namespaces
Corresponding cpplint.py check name: `build/namespaces`.
Options
-------
.. option:: HeaderFileExtensions
A comma-separated list of filename extensions of header files (the filename
extensions should not include "." prefix). Default is "h,hh,hpp,hxx".
For header files without an extension, use an empty string (if there are no
other desired extensions) or leave an empty element in the list. e.g.,
"h,hh,hpp,hxx," (note the trailing comma).
.. title:: clang-tidy - google-build-using-namespace
google-build-using-namespace
============================
Finds ``using namespace`` directives.
The check implements the following rule of the
`Google C++ Style Guide <https://google.github.io/styleguide/cppguide.html#Namespaces>`_:
You may not use a using-directive to make all names from a namespace
available.
.. code-block:: c++
// Forbidden -- This pollutes the namespace.
using namespace foo;
Corresponding cpplint.py check name: `build/namespaces`.
.. title:: clang-tidy - google-default-arguments
google-default-arguments
========================
Checks that default arguments are not given for virtual methods.
See https://google.github.io/styleguide/cppguide.html#Default_Arguments
.. title:: clang-tidy - google-explicit-constructor
google-explicit-constructor
===========================
Checks that constructors callable with a single argument and conversion
operators are marked explicit to avoid the risk of unintentional implicit
conversions.
Consider this example:
.. code-block:: c++
struct S {
int x;
operator bool() const { return true; }
};
bool f() {
S a{1};
S b{2};
return a == b;
}
The function will return ``true``, since the objects are implicitly converted to
``bool`` before comparison, which is unlikely to be the intent.
The check will suggest inserting ``explicit`` before the constructor or
conversion operator declaration. However, copy and move constructors should not
be explicit, as well as constructors taking a single ``initializer_list``
argument.
This code:
.. code-block:: c++
struct S {
S(int a);
explicit S(const S&);
operator bool() const;
...
will become
.. code-block:: c++
struct S {
explicit S(int a);
S(const S&);
explicit operator bool() const;
...
See https://google.github.io/styleguide/cppguide.html#Explicit_Constructors
.. title:: clang-tidy - google-global-names-in-headers
google-global-names-in-headers
==============================
Flag global namespace pollution in header files. Right now it only triggers on
``using`` declarations and directives.
The relevant style guide section is
https://google.github.io/styleguide/cppguide.html#Namespaces.
Options
-------
.. option:: HeaderFileExtensions
A comma-separated list of filename extensions of header files (the filename
extensions should not contain "." prefix). Default is "h".
For header files without an extension, use an empty string (if there are no
other desired extensions) or leave an empty element in the list. e.g.,
"h,hh,hpp,hxx," (note the trailing comma).
.. title:: clang-tidy - google-objc-avoid-nsobject-new
google-objc-avoid-nsobject-new
==============================
Finds calls to ``+new`` or overrides of it, which are prohibited by the
Google Objective-C style guide.
The Google Objective-C style guide forbids calling ``+new`` or overriding it in
class implementations, preferring ``+alloc`` and ``-init`` methods to
instantiate objects.
An example:
.. code-block:: objc
NSDate *now = [NSDate new];
Foo *bar = [Foo new];
Instead, code should use ``+alloc``/``-init`` or class factory methods.
.. code-block:: objc
NSDate *now = [NSDate date];
Foo *bar = [[Foo alloc] init];
This check corresponds to the Google Objective-C Style Guide rule
`Do Not Use +new
<https://google.github.io/styleguide/objcguide.html#do-not-use-new>`_.
.. title:: clang-tidy - google-objc-avoid-throwing-exception
google-objc-avoid-throwing-exception
====================================
Finds uses of throwing exceptions usages in Objective-C files.
For the same reason as the Google C++ style guide, we prefer not throwing
exceptions from Objective-C code.
The corresponding C++ style guide rule:
https://google.github.io/styleguide/cppguide.html#Exceptions
Instead, prefer passing in ``NSError **`` and return ``BOOL`` to indicate success or failure.
A counterexample:
.. code-block:: objc
- (void)readFile {
if ([self isError]) {
@throw [NSException exceptionWithName:...];
}
}
Instead, returning an error via ``NSError **`` is preferred:
.. code-block:: objc
- (BOOL)readFileWithError:(NSError **)error {
if ([self isError]) {
*error = [NSError errorWithDomain:...];
return NO;
}
return YES;
}
The corresponding style guide rule:
https://google.github.io/styleguide/objcguide.html#avoid-throwing-exceptions
.. title:: clang-tidy - google-objc-function-naming
google-objc-function-naming
===========================
Finds function declarations in Objective-C files that do not follow the pattern
described in the Google Objective-C Style Guide.
The corresponding style guide rule can be found here:
https://google.github.io/styleguide/objcguide.html#function-names
All function names should be in Pascal case. Functions whose storage class is
not static should have an appropriate prefix.
The following code sample does not follow this pattern:
.. code-block:: objc
static bool is_positive(int i) { return i > 0; }
bool IsNegative(int i) { return i < 0; }
The sample above might be corrected to the following code:
.. code-block:: objc
static bool IsPositive(int i) { return i > 0; }
bool *ABCIsNegative(int i) { return i < 0; }
.. title:: clang-tidy - google-objc-global-variable-declaration
google-objc-global-variable-declaration
=======================================
Finds global variable declarations in Objective-C files that do not follow the
pattern of variable names in Google's Objective-C Style Guide.
The corresponding style guide rule:
https://google.github.io/styleguide/objcguide.html#variable-names
All the global variables should follow the pattern of ``g[A-Z].*`` (variables) or
``k[A-Z].*`` (constants). The check will suggest a variable name that follows the
pattern if it can be inferred from the original name.
For code:
.. code-block:: objc
static NSString* myString = @"hello";
The fix will be:
.. code-block:: objc
static NSString* gMyString = @"hello";
Another example of constant:
.. code-block:: objc
static NSString* const myConstString = @"hello";
The fix will be:
.. code-block:: objc
static NSString* const kMyConstString = @"hello";
However for code that prefixed with non-alphabetical characters like:
.. code-block:: objc
static NSString* __anotherString = @"world";
The check will give a warning message but will not be able to suggest a fix. The
user needs to fix it on their own.
.. title:: clang-tidy - google-readability-avoid-underscore-in-googletest-name
google-readability-avoid-underscore-in-googletest-name
======================================================
Checks whether there are underscores in googletest test and test case names in
test macros:
- ``TEST``
- ``TEST_F``
- ``TEST_P``
- ``TYPED_TEST``
- ``TYPED_TEST_P``
The ``FRIEND_TEST`` macro is not included.
For example:
.. code-block:: c++
TEST(TestCaseName, Illegal_TestName) {}
TEST(Illegal_TestCaseName, TestName) {}
would trigger the check. `Underscores are not allowed`_ in test names nor test
case names.
The ``DISABLED_`` prefix, which may be used to `disable individual tests`_, is
ignored when checking test names, but the rest of the rest of the test name is
still checked.
This check does not propose any fixes.
.. _Underscores are not allowed: https://github.com/google/googletest/blob/master/googletest/docs/faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore
.. _disable individual tests: https://github.com/google/googletest/blob/master/googletest/docs/faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore
.. title:: clang-tidy - google-readability-braces-around-statements
.. meta::
:http-equiv=refresh: 5;URL=readability-braces-around-statements.html
google-readability-braces-around-statements
===========================================
The google-readability-braces-around-statements check is an alias, please see
`readability-braces-around-statements <readability-braces-around-statements.html>`_
for more information.
.. title:: clang-tidy - google-readability-casting
google-readability-casting
==========================
Finds usages of C-style casts.
https://google.github.io/styleguide/cppguide.html#Casting
Corresponding cpplint.py check name: `readability/casting`.
This check is similar to ``-Wold-style-cast``, but it suggests automated fixes
in some cases. The reported locations should not be different from the
ones generated by ``-Wold-style-cast``.
.. title:: clang-tidy - google-readability-function-size
.. meta::
:http-equiv=refresh: 5;URL=readability-function-size.html
google-readability-function-size
================================
The google-readability-function-size check is an alias, please see
`readability-function-size <readability-function-size.html>`_ for more
information.
.. title:: clang-tidy - google-readability-namespace-comments
.. meta::
:http-equiv=refresh: 5;URL=llvm-namespace-comment.html
google-readability-namespace-comments
=====================================
The google-readability-namespace-comments check is an alias, please see
`llvm-namespace-comment <llvm-namespace-comment.html>`_ for more information.
.. title:: clang-tidy - google-readability-todo
google-readability-todo
=======================
Finds TODO comments without a username or bug number.
The relevant style guide section is
https://google.github.io/styleguide/cppguide.html#TODO_Comments.
Corresponding cpplint.py check: `readability/todo`
.. title:: clang-tidy - google-runtime-int
google-runtime-int
==================
Finds uses of ``short``, ``long`` and ``long long`` and suggest replacing them
with ``u?intXX(_t)?``.
The corresponding style guide rule:
https://google.github.io/styleguide/cppguide.html#Integer_Types.
Corresponding cpplint.py check: `runtime/int`.
Options
-------
.. option:: UnsignedTypePrefix
A string specifying the unsigned type prefix. Default is `uint`.
.. option:: SignedTypePrefix
A string specifying the signed type prefix. Default is `int`.
.. option:: TypeSuffix
A string specifying the type suffix. Default is an empty string.
.. title:: clang-tidy - google-runtime-operator
google-runtime-operator
=======================
Finds overloads of unary ``operator &``.
https://google.github.io/styleguide/cppguide.html#Operator_Overloading
Corresponding cpplint.py check name: `runtime/operator`.
.. title:: clang-tidy - google-upgrade-googletest-case
google-upgrade-googletest-case
==============================
Finds uses of deprecated Google Test version 1.9 APIs with names containing
``case`` and replaces them with equivalent APIs with ``suite``.
All names containing ``case`` are being replaced to be consistent with the
meanings of "test case" and "test suite" as used by the International
Software Testing Qualifications Board and ISO 29119.
The new names are a part of Google Test version 1.9 (release pending). It is
recommended that users update their dependency to version 1.9 and then use this
check to remove deprecated names.
The affected APIs are:
- Member functions of ``testing::Test``, ``testing::TestInfo``,
``testing::TestEventListener``, ``testing::UnitTest``, and any type inheriting
from these types
- The macros ``TYPED_TEST_CASE``, ``TYPED_TEST_CASE_P``,
``REGISTER_TYPED_TEST_CASE_P``, and ``INSTANTIATE_TYPED_TEST_CASE_P``
- The type alias ``testing::TestCase``
Examples of fixes created by this check:
.. code-block:: c++
class FooTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
};
TYPED_TEST_CASE(BarTest, BarTypes);
becomes
.. code-block:: c++
class FooTest : public testing::Test {
public:
static void SetUpTestSuite();
static void TearDownTestSuite();
};
TYPED_TEST_SUITE(BarTest, BarTypes);
For better consistency of user code, the check renames both virtual and
non-virtual member functions with matching names in derived types. The check
tries to provide a only warning when a fix cannot be made safely, as is the case
with some template and macro uses.
.. title:: clang-tidy - hicpp-avoid-c-arrays
.. meta::
:http-equiv=refresh: 5;URL=modernize-avoid-c-arrays.html
hicpp-avoid-c-arrays
====================
The hicpp-avoid-c-arrays check is an alias, please see
`modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_
for more information.
.. title:: clang-tidy - hicpp-avoid-goto
hicpp-avoid-goto
================
The `hicpp-avoid-goto` check is an alias to
`cppcoreguidelines-avoid-goto <cppcoreguidelines-avoid-goto.html>`_.
Rule `6.3.1 High Integrity C++ <http://www.codingstandard.com/rule/6-3-1-ensure-that-the-labels-for-a-jump-statement-or-a-switch-condition-appear-later-in-the-same-or-an-enclosing-block/>`_
requires that ``goto`` only skips parts of a block and is not used for other
reasons.
Both coding guidelines implement the same exception to the usage of ``goto``.
.. title:: clang-tidy - hicpp-braces-around-statements
.. meta::
:http-equiv=refresh: 5;URL=readability-braces-around-statements.html
hicpp-braces-around-statements
==============================
The `hicpp-braces-around-statements` check is an alias, please see
`readability-braces-around-statements <readability-braces-around-statements.html>`_
for more information.
It enforces the `rule 6.1.1 <http://www.codingstandard.com/rule/6-1-1-enclose-the-body-of-a-selection-or-an-iteration-statement-in-a-compound-statement/>`_.
.. title:: clang-tidy - hicpp-deprecated-headers
.. meta::
:http-equiv=refresh: 5;URL=modernize-deprecated-headers.html
hicpp-deprecated-headers
========================
The `hicpp-deprecated-headers` check is an alias, please see
`modernize-deprecated-headers <modernize-deprecated-headers.html>`_
for more information.
It enforces the `rule 1.3.3 <http://www.codingstandard.com/rule/1-3-3-do-not-use-the-c-standard-library-h-headers/>`_.
.. title:: clang-tidy - hicpp-exception-baseclass
hicpp-exception-baseclass
=========================
Ensure that every value that in a ``throw`` expression is an instance of
``std::exception``.
This enforces `rule 15.1 <http://www.codingstandard.com/section/15-1-throwing-an-exception/>`_
of the High Integrity C++ Coding Standard.
.. code-block:: c++
class custom_exception {};
void throwing() noexcept(false) {
// Problematic throw expressions.
throw int(42);
throw custom_exception();
}
class mathematical_error : public std::exception {};
void throwing2() noexcept(false) {
// These kind of throws are ok.
throw mathematical_error();
throw std::runtime_error();
throw std::exception();
}
.. title:: clang-tidy - hicpp-explicit-conversions
.. meta::
:http-equiv=refresh: 5;URL=google-explicit-constructor.html
hicpp-explicit-conversions
==========================
This check is an alias for `google-explicit-constructor <google-explicit-constructor.html>`_.
Used to enforce parts of `rule 5.4.1 <http://www.codingstandard.com/rule/5-4-1-only-use-casting-forms-static_cast-excl-void-dynamic_cast-or-explicit-constructor-call/>`_.
This check will enforce that constructors and conversion operators are marked `explicit`.
Other forms of casting checks are implemented in other places.
The following checks can be used to check for more forms of casting:
- `cppcoreguidelines-pro-type-static-cast-downcast <cppcoreguidelines-pro-type-static-cast-downcast.html>`_
- `cppcoreguidelines-pro-type-reinterpret-cast <cppcoreguidelines-pro-type-reinterpret-cast.html>`_
- `cppcoreguidelines-pro-type-const-cast <cppcoreguidelines-pro-type-const-cast.html>`_
- `cppcoreguidelines-pro-type-cstyle-cast <cppcoreguidelines-pro-type-cstyle-cast.html>`_
.. title:: clang-tidy - hicpp-function-size
.. meta::
:http-equiv=refresh: 5;URL=readability-function-size.html
hicpp-function-size
===================
This check is an alias for `readability-function-size <readability-function-size.html>`_.
Useful to enforce multiple sections on function complexity.
- `rule 8.2.2 <http://www.codingstandard.com/rule/8-2-2-do-not-declare-functions-with-an-excessive-number-of-parameters/>`_
- `rule 8.3.1 <http://www.codingstandard.com/rule/8-3-1-do-not-write-functions-with-an-excessive-mccabe-cyclomatic-complexity/>`_
- `rule 8.3.2 <http://www.codingstandard.com/rule/8-3-2-do-not-write-functions-with-a-high-static-program-path-count/>`_
.. title:: clang-tidy - hicpp-invalid-access-moved
.. meta::
:http-equiv=refresh: 5;URL=bugprone-use-after-move.html
hicpp-invalid-access-moved
==========================
This check is an alias for `bugprone-use-after-move <bugprone-use-after-move.html>`_.
Implements parts of the `rule 8.4.1 <http://www.codingstandard.com/rule/8-4-1-do-not-access-an-invalid-object-or-an-object-with-indeterminate-value/>`_ to check if moved-from objects are accessed.
.. title:: clang-tidy - hicpp-member-init
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-pro-type-member-init.html
hicpp-member-init
=================
This check is an alias for `cppcoreguidelines-pro-type-member-init <cppcoreguidelines-pro-type-member-init.html>`_.
Implements the check for
`rule 12.4.2 <http://www.codingstandard.com/rule/12-4-2-ensure-that-a-constructor-initializes-explicitly-all-base-classes-and-non-static-data-members/>`_
to initialize class members in the right order.
.. title:: clang-tidy - hicpp-move-const-arg
.. meta::
:http-equiv=refresh: 5;URL=performance-move-const-arg.html
hicpp-move-const-arg
====================
The `hicpp-move-const-arg` check is an alias, please see
`performance-move-const-arg <performance-move-const-arg.html>`_ for more information.
It enforces the `rule 17.3.1 <http://www.codingstandard.com/rule/17-3-1-do-not-use-stdmove-on-objects-declared-with-const-or-const-type/>`_.
.. title:: clang-tidy - hicpp-multiway-paths-covered
hicpp-multiway-paths-covered
============================
This check discovers situations where code paths are not fully-covered.
It furthermore suggests using ``if`` instead of ``switch`` if the code will be more clear.
The `rule 6.1.2 <http://www.codingstandard.com/rule/6-1-2-explicitly-cover-all-paths-through-multi-way-selection-statements/>`_
and `rule 6.1.4 <http://www.codingstandard.com/rule/6-1-4-ensure-that-a-switch-statement-has-at-least-two-case-labels-distinct-from-the-default-label/>`_
of the High Integrity C++ Coding Standard are enforced.
``if-else if`` chains that miss a final ``else`` branch might lead to unexpected
program execution and be the result of a logical error.
If the missing ``else`` branch is intended you can leave it empty with a clarifying
comment.
This warning can be noisy on some code bases, so it is disabled by default.
.. code-block:: c++
void f1() {
int i = determineTheNumber();
if(i > 0) {
// Some Calculation
} else if (i < 0) {
// Precondition violated or something else.
}
// ...
}
Similar arguments hold for ``switch`` statements which do not cover all possible code paths.
.. code-block:: c++
// The missing default branch might be a logical error. It can be kept empty
// if there is nothing to do, making it explicit.
void f2(int i) {
switch (i) {
case 0: // something
break;
case 1: // something else
break;
}
// All other numbers?
}
// Violates this rule as well, but already emits a compiler warning (-Wswitch).
enum Color { Red, Green, Blue, Yellow };
void f3(enum Color c) {
switch (c) {
case Red: // We can't drive for now.
break;
case Green: // We are allowed to drive.
break;
}
// Other cases missing
}
The `rule 6.1.4 <http://www.codingstandard.com/rule/6-1-4-ensure-that-a-switch-statement-has-at-least-two-case-labels-distinct-from-the-default-label/>`_
requires every ``switch`` statement to have at least two ``case`` labels other than a `default` label.
Otherwise, the ``switch`` could be better expressed with an ``if`` statement.
Degenerated ``switch`` statements without any labels are caught as well.
.. code-block:: c++
// Degenerated switch that could be better written as `if`
int i = 42;
switch(i) {
case 1: // do something here
default: // do somethe else here
}
// Should rather be the following:
if (i == 1) {
// do something here
}
else {
// do something here
}
.. code-block:: c++
// A completely degenerated switch will be diagnosed.
int i = 42;
switch(i) {}
Options
-------
.. option:: WarnOnMissingElse
Boolean flag that activates a warning for missing ``else`` branches.
Default is `false`.
.. title:: clang-tidy - hicpp-named-parameter
.. meta::
:http-equiv=refresh: 5;URL=readability-named-parameter.html
hicpp-named-parameter
=====================
This check is an alias for `readability-named-parameter <readability-named-parameter.html>`_.
Implements `rule 8.2.1 <http://www.codingstandard.com/rule/8-2-1-make-parameter-names-absent-or-identical-in-all-declarations/>`_.
.. title:: clang-tidy - hicpp-new-delete-operators
.. meta::
:http-equiv=refresh: 5;URL=misc-new-delete-overloads.html
hicpp-new-delete-operators
==========================
This check is an alias for `misc-new-delete-overloads <misc-new-delete-overloads.html>`_.
Implements `rule 12.3.1 <http://www.codingstandard.com/section/12-3-free-store/>`_ to ensure
the `new` and `delete` operators have the correct signature.
.. title:: clang-tidy - hicpp-no-array-decay
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-pro-bounds-array-to-pointer-decay.html
hicpp-no-array-decay
====================
The `hicpp-no-array-decay` check is an alias, please see
`cppcoreguidelines-pro-bounds-array-to-pointer-decay <cppcoreguidelines-pro-bounds-array-to-pointer-decay.html>`_
for more information.
It enforces the `rule 4.1.1 <http://www.codingstandard.com/section/4-1-array-to-pointer-conversion/>`_.
.. title:: clang-tidy - hicpp-no-assembler
hicpp-no-assembler
===================
Check for assembler statements. No fix is offered.
Inline assembler is forbidden by the `High Intergrity C++ Coding Standard
<http://www.codingstandard.com/section/7-5-the-asm-declaration/>`_
as it restricts the portability of code.
.. title:: clang-tidy - hicpp-no-malloc
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-no-malloc.html
hicpp-no-malloc
===============
The `hicpp-no-malloc` check is an alias, please see
`cppcoreguidelines-no-malloc <cppcoreguidelines-no-malloc.html>`_
for more information.
It enforces the `rule 5.3.2 <http://www.codingstandard.com/rule/5-3-2-allocate-memory-using-new-and-release-it-using-delete/>`_.
.. title:: clang-tidy - hicpp-noexcept-move
.. meta::
:http-equiv=refresh: 5;URL=performance-noexcept-move-constructor.html
hicpp-noexcept-move
===================
This check is an alias for `performance-noexcept-move-constructor <performance-noexcept-move-constructor.html>`_.
Checks `rule 12.5.4 <http://www.codingstandard.com/rule/12-5-4-declare-noexcept-the-move-constructor-and-move-assignment-operator>`_ to mark move assignment and move construction `noexcept`.
.. title:: clang-tidy - hicpp-signed-bitwise
hicpp-signed-bitwise
====================
Finds uses of bitwise operations on signed integer types, which may lead to
undefined or implementation defined behaviour.
The according rule is defined in the `High Integrity C++ Standard, Section 5.6.1 <http://www.codingstandard.com/section/5-6-shift-operators/>`_.
Options
-------
.. option:: IgnorePositiveIntegerLiterals
If this option is set to `true`, the check will not warn on bitwise operations with positive integer literals, e.g. `~0`, `2 << 1`, etc.
Default value is `false`.
.. title:: clang-tidy - hicpp-special-member-functions
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-special-member-functions.html
hicpp-special-member-functions
==============================
This check is an alias for `cppcoreguidelines-special-member-functions <cppcoreguidelines-special-member-functions.html>`_.
Checks that special member functions have the correct signature, according to `rule 12.5.7 <http://www.codingstandard.com/rule/12-5-7-declare-assignment-operators-with-the-ref-qualifier/>`_.
.. title:: clang-tidy - hicpp-static-assert
.. meta::
:http-equiv=refresh: 5;URL=misc-static-assert.html
hicpp-static-assert
===================
The `hicpp-static-assert` check is an alias, please see
`misc-static-assert <misc-static-assert.html>`_ for more information.
It enforces the `rule 7.1.10 <http://www.codingstandard.com/rule/6-1-1-enclose-the-body-of-a-selection-or-an-iteration-statement-in-a-compound-statement/>`_.
.. title:: clang-tidy - hicpp-undelegated-constructor
.. meta::
:http-equiv=refresh: 5;URL=bugprone-undelegated-constructor.html
hicpp-undelegated-constructor
=============================
This check is an alias for `bugprone-undelegated-constructor <bugprone-undelegated-constructor.html>`_.
Partially implements `rule 12.4.5 <http://www.codingstandard.com/rule/12-4-5-use-delegating-constructors-to-reduce-code-duplication/>`_
to find misplaced constructor calls inside a constructor.
.. code-block:: c++
struct Ctor {
Ctor();
Ctor(int);
Ctor(int, int);
Ctor(Ctor *i) {
// All Ctor() calls result in a temporary object
Ctor(); // did you intend to call a delegated constructor?
Ctor(0); // did you intend to call a delegated constructor?
Ctor(1, 2); // did you intend to call a delegated constructor?
foo();
}
};
.. title:: clang-tidy - hicpp-uppercase-literal-suffix
.. meta::
:http-equiv=refresh: 5;URL=readability-uppercase-literal-suffix.html
hicpp-uppercase-literal-suffix
==============================
The hicpp-uppercase-literal-suffix check is an alias, please see
`readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_ for more information.
.. title:: clang-tidy - hicpp-use-auto
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-auto.html
hicpp-use-auto
==============
The `hicpp-use-auto` check is an alias, please see
`modernize-use-auto <modernize-use-auto.html>`_ for more information.
It enforces the `rule 7.1.8 <http://www.codingstandard.com/rule/7-1-8-use-auto-id-expr-when-declaring-a-variable-to-have-the-same-type-as-its-initializer-function-call/>`_.
.. title:: clang-tidy - hicpp-use-emplace
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-emplace.html
hicpp-use-emplace
=================
The `hicpp-use-emplace` check is an alias, please see
`modernize-use-emplace <modernize-use-emplace.html>`_ for more information.
It enforces the `rule 17.4.2 <http://www.codingstandard.com/rule/17-4-2-use-api-calls-that-construct-objects-in-place/>`_.
.. title:: clang-tidy - hicpp-use-equals-defaults
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-equals-default.html
hicpp-use-equals-default
========================
This check is an alias for `modernize-use-equals-default <modernize-use-equals-default.html>`_.
Implements `rule 12.5.1 <http://www.codingstandard.com/rule/12-5-1-define-explicitly-default-or-delete-implicit-special-member-functions-of-concrete-classes/>`_ to explicitly default special member functions.
.. title:: clang-tidy - hicpp-use-equals-delete
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-equals-delete.html
hicpp-use-equals-delete
=======================
This check is an alias for `modernize-use-equals-delete <modernize-use-equals-delete.html>`_.
Implements `rule 12.5.1 <http://www.codingstandard.com/rule/12-5-1-define-explicitly-default-or-delete-implicit-special-member-functions-of-concrete-classes/>`_
to explicitly default or delete special member functions.
.. title:: clang-tidy - hicpp-use-noexcept
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-noexcept.html
hicpp-use-noexcept
==================
The `hicpp-use-noexcept` check is an alias, please see
`modernize-use-noexcept <modernize-use-noexcept.html>`_ for more information.
It enforces the `rule 1.3.5 <http://www.codingstandard.com/rule/1-3-5-do-not-use-throw-exception-specifications/>`_.
.. title:: clang-tidy - hicpp-use-nullptr
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-nullptr.html
hicpp-use-nullptr
=================
The `hicpp-use-nullptr` check is an alias, please see
`modernize-use-nullptr <modernize-use-nullptr.html>`_ for more information.
It enforces the `rule 2.5.3 <http://www.codingstandard.com/rule/2-5-3-use-nullptr-for-the-null-pointer-constant/>`_.
.. title:: clang-tidy - hicpp-use-override
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-override.html
hicpp-use-override
==================
This check is an alias for `modernize-use-override <modernize-use-override.html>`_.
Implements `rule 10.2.1 <http://www.codingstandard.com/section/10-2-virtual-functions/>`_ to
declare a virtual function `override` when overriding.
.. title:: clang-tidy - hicpp-vararg
.. meta::
:http-equiv=refresh: 5;URL=cppcoreguidelines-pro-type-vararg.html
hicpp-vararg
============
The `hicpp-vararg` check is an alias, please see
`cppcoreguidelines-pro-type-vararg <cppcoreguidelines-pro-type-vararg.html>`_
for more information.
It enforces the `rule 14.1.1 <http://www.codingstandard.com/section/14-1-template-declarations/>`_.
.. title:: clang-tidy - linuxkernel-must-use-errs
linuxkernel-must-use-errs
=========================
Checks Linux kernel code to see if it uses the results from the functions in
``linux/err.h``. Also checks to see if code uses the results from functions that
directly return a value from one of these error functions.
This is important in the Linux kernel because ``ERR_PTR``, ``PTR_ERR``,
``IS_ERR``, ``IS_ERR_OR_NULL``, ``ERR_CAST``, and ``PTR_ERR_OR_ZERO`` return
values must be checked, since positive pointers and negative error codes are
being used in the same context. These functions are marked with
``__attribute__((warn_unused_result))``, but some kernel versions do not have
this warning enabled for clang.
Examples:
.. code-block:: c
/* Trivial unused call to an ERR function */
PTR_ERR_OR_ZERO(some_function_call());
/* A function that returns ERR_PTR. */
void *fn() { ERR_PTR(-EINVAL); }
/* An invalid use of fn. */
fn();
.. title:: clang-tidy - Clang-Tidy Checks
Clang-Tidy Checks
=================
.. toctree::
:glob:
:hidden:
*
.. csv-table::
:header: "Name", "Offers fixes"
`abseil-duration-addition <abseil-duration-addition.html>`_, "Yes"
`abseil-duration-comparison <abseil-duration-comparison.html>`_, "Yes"
`abseil-duration-conversion-cast <abseil-duration-conversion-cast.html>`_, "Yes"
`abseil-duration-division <abseil-duration-division.html>`_, "Yes"
`abseil-duration-factory-float <abseil-duration-factory-float.html>`_, "Yes"
`abseil-duration-factory-scale <abseil-duration-factory-scale.html>`_, "Yes"
`abseil-duration-subtraction <abseil-duration-subtraction.html>`_, "Yes"
`abseil-duration-unnecessary-conversion <abseil-duration-unnecessary-conversion.html>`_, "Yes"
`abseil-faster-strsplit-delimiter <abseil-faster-strsplit-delimiter.html>`_, "Yes"
`abseil-no-internal-dependencies <abseil-no-internal-dependencies.html>`_,
`abseil-no-namespace <abseil-no-namespace.html>`_,
`abseil-redundant-strcat-calls <abseil-redundant-strcat-calls.html>`_, "Yes"
`abseil-str-cat-append <abseil-str-cat-append.html>`_, "Yes"
`abseil-string-find-startswith <abseil-string-find-startswith.html>`_, "Yes"
`abseil-string-find-str-contains <abseil-string-find-str-contains.html>`_, "Yes"
`abseil-time-comparison <abseil-time-comparison.html>`_, "Yes"
`abseil-time-subtraction <abseil-time-subtraction.html>`_, "Yes"
`abseil-upgrade-duration-conversions <abseil-upgrade-duration-conversions.html>`_, "Yes"
`altera-id-dependent-backward-branch <altera-id-dependent-backward-branch.html>`_,
`altera-kernel-name-restriction <altera-kernel-name-restriction.html>`_,
`altera-single-work-item-barrier <altera-single-work-item-barrier.html>`_,
`altera-struct-pack-align <altera-struct-pack-align.html>`_, "Yes"
`altera-unroll-loops <altera-unroll-loops.html>`_,
`android-cloexec-accept <android-cloexec-accept.html>`_, "Yes"
`android-cloexec-accept4 <android-cloexec-accept4.html>`_,
`android-cloexec-creat <android-cloexec-creat.html>`_, "Yes"
`android-cloexec-dup <android-cloexec-dup.html>`_, "Yes"
`android-cloexec-epoll-create <android-cloexec-epoll-create.html>`_,
`android-cloexec-epoll-create1 <android-cloexec-epoll-create1.html>`_,
`android-cloexec-fopen <android-cloexec-fopen.html>`_,
`android-cloexec-inotify-init <android-cloexec-inotify-init.html>`_,
`android-cloexec-inotify-init1 <android-cloexec-inotify-init1.html>`_,
`android-cloexec-memfd-create <android-cloexec-memfd-create.html>`_,
`android-cloexec-open <android-cloexec-open.html>`_,
`android-cloexec-pipe <android-cloexec-pipe.html>`_, "Yes"
`android-cloexec-pipe2 <android-cloexec-pipe2.html>`_,
`android-cloexec-socket <android-cloexec-socket.html>`_,
`android-comparison-in-temp-failure-retry <android-comparison-in-temp-failure-retry.html>`_,
`boost-use-to-string <boost-use-to-string.html>`_, "Yes"
`bugprone-argument-comment <bugprone-argument-comment.html>`_, "Yes"
`bugprone-assert-side-effect <bugprone-assert-side-effect.html>`_,
`bugprone-bad-signal-to-kill-thread <bugprone-bad-signal-to-kill-thread.html>`_,
`bugprone-bool-pointer-implicit-conversion <bugprone-bool-pointer-implicit-conversion.html>`_, "Yes"
`bugprone-branch-clone <bugprone-branch-clone.html>`_,
`bugprone-copy-constructor-init <bugprone-copy-constructor-init.html>`_, "Yes"
`bugprone-dangling-handle <bugprone-dangling-handle.html>`_,
`bugprone-dynamic-static-initializers <bugprone-dynamic-static-initializers.html>`_,
`bugprone-exception-escape <bugprone-exception-escape.html>`_,
`bugprone-fold-init-type <bugprone-fold-init-type.html>`_,
`bugprone-forward-declaration-namespace <bugprone-forward-declaration-namespace.html>`_,
`bugprone-forwarding-reference-overload <bugprone-forwarding-reference-overload.html>`_,
`bugprone-implicit-widening-of-multiplication-result <bugprone-implicit-widening-of-multiplication-result.html>`_, "Yes"
`bugprone-inaccurate-erase <bugprone-inaccurate-erase.html>`_, "Yes"
`bugprone-incorrect-roundings <bugprone-incorrect-roundings.html>`_,
`bugprone-infinite-loop <bugprone-infinite-loop.html>`_,
`bugprone-integer-division <bugprone-integer-division.html>`_,
`bugprone-lambda-function-name <bugprone-lambda-function-name.html>`_,
`bugprone-macro-parentheses <bugprone-macro-parentheses.html>`_, "Yes"
`bugprone-macro-repeated-side-effects <bugprone-macro-repeated-side-effects.html>`_,
`bugprone-misplaced-operator-in-strlen-in-alloc <bugprone-misplaced-operator-in-strlen-in-alloc.html>`_, "Yes"
`bugprone-misplaced-pointer-arithmetic-in-alloc <bugprone-misplaced-pointer-arithmetic-in-alloc.html>`_, "Yes"
`bugprone-misplaced-widening-cast <bugprone-misplaced-widening-cast.html>`_,
`bugprone-move-forwarding-reference <bugprone-move-forwarding-reference.html>`_, "Yes"
`bugprone-multiple-statement-macro <bugprone-multiple-statement-macro.html>`_,
`bugprone-no-escape <bugprone-no-escape.html>`_,
`bugprone-not-null-terminated-result <bugprone-not-null-terminated-result.html>`_, "Yes"
`bugprone-parent-virtual-call <bugprone-parent-virtual-call.html>`_, "Yes"
`bugprone-posix-return <bugprone-posix-return.html>`_, "Yes"
`bugprone-redundant-branch-condition <bugprone-redundant-branch-condition.html>`_, "Yes"
`bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_, "Yes"
`bugprone-signal-handler <bugprone-signal-handler.html>`_,
`bugprone-signed-char-misuse <bugprone-signed-char-misuse.html>`_,
`bugprone-sizeof-container <bugprone-sizeof-container.html>`_,
`bugprone-sizeof-expression <bugprone-sizeof-expression.html>`_,
`bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_,
`bugprone-string-constructor <bugprone-string-constructor.html>`_, "Yes"
`bugprone-string-integer-assignment <bugprone-string-integer-assignment.html>`_, "Yes"
`bugprone-string-literal-with-embedded-nul <bugprone-string-literal-with-embedded-nul.html>`_,
`bugprone-suspicious-enum-usage <bugprone-suspicious-enum-usage.html>`_,
`bugprone-suspicious-include <bugprone-suspicious-include.html>`_,
`bugprone-suspicious-memset-usage <bugprone-suspicious-memset-usage.html>`_, "Yes"
`bugprone-suspicious-missing-comma <bugprone-suspicious-missing-comma.html>`_,
`bugprone-suspicious-semicolon <bugprone-suspicious-semicolon.html>`_, "Yes"
`bugprone-suspicious-string-compare <bugprone-suspicious-string-compare.html>`_, "Yes"
`bugprone-swapped-arguments <bugprone-swapped-arguments.html>`_, "Yes"
`bugprone-terminating-continue <bugprone-terminating-continue.html>`_, "Yes"
`bugprone-throw-keyword-missing <bugprone-throw-keyword-missing.html>`_,
`bugprone-too-small-loop-variable <bugprone-too-small-loop-variable.html>`_,
`bugprone-undefined-memory-manipulation <bugprone-undefined-memory-manipulation.html>`_,
`bugprone-undelegated-constructor <bugprone-undelegated-constructor.html>`_,
`bugprone-unhandled-exception-at-new <bugprone-unhandled-exception-at-new.html>`_,
`bugprone-unhandled-self-assignment <bugprone-unhandled-self-assignment.html>`_,
`bugprone-unused-raii <bugprone-unused-raii.html>`_, "Yes"
`bugprone-unused-return-value <bugprone-unused-return-value.html>`_,
`bugprone-use-after-move <bugprone-use-after-move.html>`_,
`bugprone-virtual-near-miss <bugprone-virtual-near-miss.html>`_, "Yes"
`cert-dcl21-cpp <cert-dcl21-cpp.html>`_,
`cert-dcl50-cpp <cert-dcl50-cpp.html>`_,
`cert-dcl58-cpp <cert-dcl58-cpp.html>`_,
`cert-env33-c <cert-env33-c.html>`_,
`cert-err34-c <cert-err34-c.html>`_,
`cert-err52-cpp <cert-err52-cpp.html>`_,
`cert-err58-cpp <cert-err58-cpp.html>`_,
`cert-err60-cpp <cert-err60-cpp.html>`_,
`cert-flp30-c <cert-flp30-c.html>`_,
`cert-mem57-cpp <cert-mem57-cpp.html>`_,
`cert-msc50-cpp <cert-msc50-cpp.html>`_,
`cert-msc51-cpp <cert-msc51-cpp.html>`_,
`cert-oop57-cpp <cert-oop57-cpp.html>`_,
`cert-oop58-cpp <cert-oop58-cpp.html>`_,
`clang-analyzer-core.DynamicTypePropagation <clang-analyzer-core.DynamicTypePropagation.html>`_,
`clang-analyzer-core.uninitialized.CapturedBlockVariable <clang-analyzer-core.uninitialized.CapturedBlockVariable.html>`_,
`clang-analyzer-cplusplus.InnerPointer <clang-analyzer-cplusplus.InnerPointer.html>`_,
`clang-analyzer-nullability.NullableReturnedFromNonnull <clang-analyzer-nullability.NullableReturnedFromNonnull.html>`_,
`clang-analyzer-optin.osx.OSObjectCStyleCast <clang-analyzer-optin.osx.OSObjectCStyleCast.html>`_,
`clang-analyzer-optin.performance.GCDAntipattern <clang-analyzer-optin.performance.GCDAntipattern.html>`_,
`clang-analyzer-optin.performance.Padding <clang-analyzer-optin.performance.Padding.html>`_,
`clang-analyzer-optin.portability.UnixAPI <clang-analyzer-optin.portability.UnixAPI.html>`_,
`clang-analyzer-osx.MIG <clang-analyzer-osx.MIG.html>`_,
`clang-analyzer-osx.NumberObjectConversion <clang-analyzer-osx.NumberObjectConversion.html>`_,
`clang-analyzer-osx.OSObjectRetainCount <clang-analyzer-osx.OSObjectRetainCount.html>`_,
`clang-analyzer-osx.ObjCProperty <clang-analyzer-osx.ObjCProperty.html>`_,
`clang-analyzer-osx.cocoa.AutoreleaseWrite <clang-analyzer-osx.cocoa.AutoreleaseWrite.html>`_,
`clang-analyzer-osx.cocoa.Loops <clang-analyzer-osx.cocoa.Loops.html>`_,
`clang-analyzer-osx.cocoa.MissingSuperCall <clang-analyzer-osx.cocoa.MissingSuperCall.html>`_,
`clang-analyzer-osx.cocoa.NonNilReturnValue <clang-analyzer-osx.cocoa.NonNilReturnValue.html>`_,
`clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak <clang-analyzer-osx.cocoa.RunLoopAutoreleaseLeak.html>`_,
`clang-analyzer-valist.CopyToSelf <clang-analyzer-valist.CopyToSelf.html>`_,
`clang-analyzer-valist.Uninitialized <clang-analyzer-valist.Uninitialized.html>`_,
`clang-analyzer-valist.Unterminated <clang-analyzer-valist.Unterminated.html>`_,
`concurrency-mt-unsafe <concurrency-mt-unsafe.html>`_,
`concurrency-thread-canceltype-asynchronous <concurrency-thread-canceltype-asynchronous.html>`_,
`cppcoreguidelines-avoid-goto <cppcoreguidelines-avoid-goto.html>`_,
`cppcoreguidelines-avoid-non-const-global-variables <cppcoreguidelines-avoid-non-const-global-variables.html>`_,
`cppcoreguidelines-init-variables <cppcoreguidelines-init-variables.html>`_, "Yes"
`cppcoreguidelines-interfaces-global-init <cppcoreguidelines-interfaces-global-init.html>`_,
`cppcoreguidelines-macro-usage <cppcoreguidelines-macro-usage.html>`_,
`cppcoreguidelines-narrowing-conversions <cppcoreguidelines-narrowing-conversions.html>`_,
`cppcoreguidelines-no-malloc <cppcoreguidelines-no-malloc.html>`_,
`cppcoreguidelines-owning-memory <cppcoreguidelines-owning-memory.html>`_,
`cppcoreguidelines-prefer-member-initializer <cppcoreguidelines-prefer-member-initializer.html>`_, "Yes"
`cppcoreguidelines-pro-bounds-array-to-pointer-decay <cppcoreguidelines-pro-bounds-array-to-pointer-decay.html>`_,
`cppcoreguidelines-pro-bounds-constant-array-index <cppcoreguidelines-pro-bounds-constant-array-index.html>`_, "Yes"
`cppcoreguidelines-pro-bounds-pointer-arithmetic <cppcoreguidelines-pro-bounds-pointer-arithmetic.html>`_,
`cppcoreguidelines-pro-type-const-cast <cppcoreguidelines-pro-type-const-cast.html>`_,
`cppcoreguidelines-pro-type-cstyle-cast <cppcoreguidelines-pro-type-cstyle-cast.html>`_, "Yes"
`cppcoreguidelines-pro-type-member-init <cppcoreguidelines-pro-type-member-init.html>`_, "Yes"
`cppcoreguidelines-pro-type-reinterpret-cast <cppcoreguidelines-pro-type-reinterpret-cast.html>`_,
`cppcoreguidelines-pro-type-static-cast-downcast <cppcoreguidelines-pro-type-static-cast-downcast.html>`_, "Yes"
`cppcoreguidelines-pro-type-union-access <cppcoreguidelines-pro-type-union-access.html>`_,
`cppcoreguidelines-pro-type-vararg <cppcoreguidelines-pro-type-vararg.html>`_,
`cppcoreguidelines-slicing <cppcoreguidelines-slicing.html>`_,
`cppcoreguidelines-special-member-functions <cppcoreguidelines-special-member-functions.html>`_,
`darwin-avoid-spinlock <darwin-avoid-spinlock.html>`_,
`darwin-dispatch-once-nonstatic <darwin-dispatch-once-nonstatic.html>`_, "Yes"
`fuchsia-default-arguments-calls <fuchsia-default-arguments-calls.html>`_,
`fuchsia-default-arguments-declarations <fuchsia-default-arguments-declarations.html>`_, "Yes"
`fuchsia-multiple-inheritance <fuchsia-multiple-inheritance.html>`_,
`fuchsia-overloaded-operator <fuchsia-overloaded-operator.html>`_,
`fuchsia-statically-constructed-objects <fuchsia-statically-constructed-objects.html>`_,
`fuchsia-trailing-return <fuchsia-trailing-return.html>`_,
`fuchsia-virtual-inheritance <fuchsia-virtual-inheritance.html>`_,
`google-build-explicit-make-pair <google-build-explicit-make-pair.html>`_,
`google-build-namespaces <google-build-namespaces.html>`_,
`google-build-using-namespace <google-build-using-namespace.html>`_,
`google-default-arguments <google-default-arguments.html>`_,
`google-explicit-constructor <google-explicit-constructor.html>`_, "Yes"
`google-global-names-in-headers <google-global-names-in-headers.html>`_,
`google-objc-avoid-nsobject-new <google-objc-avoid-nsobject-new.html>`_,
`google-objc-avoid-throwing-exception <google-objc-avoid-throwing-exception.html>`_,
`google-objc-function-naming <google-objc-function-naming.html>`_,
`google-objc-global-variable-declaration <google-objc-global-variable-declaration.html>`_,
`google-readability-avoid-underscore-in-googletest-name <google-readability-avoid-underscore-in-googletest-name.html>`_,
`google-readability-casting <google-readability-casting.html>`_,
`google-readability-todo <google-readability-todo.html>`_,
`google-runtime-int <google-runtime-int.html>`_,
`google-runtime-operator <google-runtime-operator.html>`_,
`google-upgrade-googletest-case <google-upgrade-googletest-case.html>`_, "Yes"
`hicpp-avoid-goto <hicpp-avoid-goto.html>`_,
`hicpp-exception-baseclass <hicpp-exception-baseclass.html>`_,
`hicpp-multiway-paths-covered <hicpp-multiway-paths-covered.html>`_,
`hicpp-no-assembler <hicpp-no-assembler.html>`_,
`hicpp-signed-bitwise <hicpp-signed-bitwise.html>`_,
`linuxkernel-must-use-errs <linuxkernel-must-use-errs.html>`_,
`llvm-header-guard <llvm-header-guard.html>`_,
`llvm-include-order <llvm-include-order.html>`_, "Yes"
`llvm-namespace-comment <llvm-namespace-comment.html>`_,
`llvm-prefer-isa-or-dyn-cast-in-conditionals <llvm-prefer-isa-or-dyn-cast-in-conditionals.html>`_, "Yes"
`llvm-prefer-register-over-unsigned <llvm-prefer-register-over-unsigned.html>`_, "Yes"
`llvm-twine-local <llvm-twine-local.html>`_, "Yes"
`llvmlibc-callee-namespace <llvmlibc-callee-namespace.html>`_,
`llvmlibc-implementation-in-namespace <llvmlibc-implementation-in-namespace.html>`_,
`llvmlibc-restrict-system-libc-headers <llvmlibc-restrict-system-libc-headers.html>`_, "Yes"
`misc-definitions-in-headers <misc-definitions-in-headers.html>`_, "Yes"
`misc-misplaced-const <misc-misplaced-const.html>`_,
`misc-new-delete-overloads <misc-new-delete-overloads.html>`_,
`misc-no-recursion <misc-no-recursion.html>`_,
`misc-non-copyable-objects <misc-non-copyable-objects.html>`_,
`misc-non-private-member-variables-in-classes <misc-non-private-member-variables-in-classes.html>`_,
`misc-redundant-expression <misc-redundant-expression.html>`_, "Yes"
`misc-static-assert <misc-static-assert.html>`_, "Yes"
`misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_,
`misc-unconventional-assign-operator <misc-unconventional-assign-operator.html>`_,
`misc-uniqueptr-reset-release <misc-uniqueptr-reset-release.html>`_, "Yes"
`misc-unused-alias-decls <misc-unused-alias-decls.html>`_, "Yes"
`misc-unused-parameters <misc-unused-parameters.html>`_, "Yes"
`misc-unused-using-decls <misc-unused-using-decls.html>`_, "Yes"
`modernize-avoid-bind <modernize-avoid-bind.html>`_, "Yes"
`modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_,
`modernize-concat-nested-namespaces <modernize-concat-nested-namespaces.html>`_, "Yes"
`modernize-deprecated-headers <modernize-deprecated-headers.html>`_, "Yes"
`modernize-deprecated-ios-base-aliases <modernize-deprecated-ios-base-aliases.html>`_, "Yes"
`modernize-loop-convert <modernize-loop-convert.html>`_, "Yes"
`modernize-make-shared <modernize-make-shared.html>`_, "Yes"
`modernize-make-unique <modernize-make-unique.html>`_, "Yes"
`modernize-pass-by-value <modernize-pass-by-value.html>`_, "Yes"
`modernize-raw-string-literal <modernize-raw-string-literal.html>`_, "Yes"
`modernize-redundant-void-arg <modernize-redundant-void-arg.html>`_, "Yes"
`modernize-replace-auto-ptr <modernize-replace-auto-ptr.html>`_, "Yes"
`modernize-replace-disallow-copy-and-assign-macro <modernize-replace-disallow-copy-and-assign-macro.html>`_, "Yes"
`modernize-replace-random-shuffle <modernize-replace-random-shuffle.html>`_, "Yes"
`modernize-return-braced-init-list <modernize-return-braced-init-list.html>`_, "Yes"
`modernize-shrink-to-fit <modernize-shrink-to-fit.html>`_, "Yes"
`modernize-unary-static-assert <modernize-unary-static-assert.html>`_, "Yes"
`modernize-use-auto <modernize-use-auto.html>`_, "Yes"
`modernize-use-bool-literals <modernize-use-bool-literals.html>`_, "Yes"
`modernize-use-default-member-init <modernize-use-default-member-init.html>`_, "Yes"
`modernize-use-emplace <modernize-use-emplace.html>`_, "Yes"
`modernize-use-equals-default <modernize-use-equals-default.html>`_, "Yes"
`modernize-use-equals-delete <modernize-use-equals-delete.html>`_, "Yes"
`modernize-use-nodiscard <modernize-use-nodiscard.html>`_, "Yes"
`modernize-use-noexcept <modernize-use-noexcept.html>`_, "Yes"
`modernize-use-nullptr <modernize-use-nullptr.html>`_, "Yes"
`modernize-use-override <modernize-use-override.html>`_, "Yes"
`modernize-use-trailing-return-type <modernize-use-trailing-return-type.html>`_, "Yes"
`modernize-use-transparent-functors <modernize-use-transparent-functors.html>`_, "Yes"
`modernize-use-uncaught-exceptions <modernize-use-uncaught-exceptions.html>`_, "Yes"
`modernize-use-using <modernize-use-using.html>`_, "Yes"
`mpi-buffer-deref <mpi-buffer-deref.html>`_, "Yes"
`mpi-type-mismatch <mpi-type-mismatch.html>`_, "Yes"
`objc-avoid-nserror-init <objc-avoid-nserror-init.html>`_,
`objc-dealloc-in-category <objc-dealloc-in-category.html>`_,
`objc-forbidden-subclassing <objc-forbidden-subclassing.html>`_,
`objc-missing-hash <objc-missing-hash.html>`_,
`objc-nsinvocation-argument-lifetime <objc-nsinvocation-argument-lifetime.html>`_, "Yes"
`objc-property-declaration <objc-property-declaration.html>`_, "Yes"
`objc-super-self <objc-super-self.html>`_, "Yes"
`openmp-exception-escape <openmp-exception-escape.html>`_,
`openmp-use-default-none <openmp-use-default-none.html>`_,
`performance-faster-string-find <performance-faster-string-find.html>`_, "Yes"
`performance-for-range-copy <performance-for-range-copy.html>`_, "Yes"
`performance-implicit-conversion-in-loop <performance-implicit-conversion-in-loop.html>`_,
`performance-inefficient-algorithm <performance-inefficient-algorithm.html>`_, "Yes"
`performance-inefficient-string-concatenation <performance-inefficient-string-concatenation.html>`_,
`performance-inefficient-vector-operation <performance-inefficient-vector-operation.html>`_, "Yes"
`performance-move-const-arg <performance-move-const-arg.html>`_, "Yes"
`performance-move-constructor-init <performance-move-constructor-init.html>`_,
`performance-no-automatic-move <performance-no-automatic-move.html>`_,
`performance-no-int-to-ptr <performance-no-int-to-ptr.html>`_,
`performance-noexcept-move-constructor <performance-noexcept-move-constructor.html>`_, "Yes"
`performance-trivially-destructible <performance-trivially-destructible.html>`_, "Yes"
`performance-type-promotion-in-math-fn <performance-type-promotion-in-math-fn.html>`_, "Yes"
`performance-unnecessary-copy-initialization <performance-unnecessary-copy-initialization.html>`_,
`performance-unnecessary-value-param <performance-unnecessary-value-param.html>`_, "Yes"
`portability-restrict-system-includes <portability-restrict-system-includes.html>`_, "Yes"
`portability-simd-intrinsics <portability-simd-intrinsics.html>`_,
`readability-avoid-const-params-in-decls <readability-avoid-const-params-in-decls.html>`_,
`readability-braces-around-statements <readability-braces-around-statements.html>`_, "Yes"
`readability-const-return-type <readability-const-return-type.html>`_, "Yes"
`readability-container-size-empty <readability-container-size-empty.html>`_, "Yes"
`readability-convert-member-functions-to-static <readability-convert-member-functions-to-static.html>`_,
`readability-delete-null-pointer <readability-delete-null-pointer.html>`_, "Yes"
`readability-else-after-return <readability-else-after-return.html>`_, "Yes"
`readability-function-cognitive-complexity <readability-function-cognitive-complexity.html>`_,
`readability-function-size <readability-function-size.html>`_,
`readability-identifier-naming <readability-identifier-naming.html>`_, "Yes"
`readability-implicit-bool-conversion <readability-implicit-bool-conversion.html>`_, "Yes"
`readability-inconsistent-declaration-parameter-name <readability-inconsistent-declaration-parameter-name.html>`_, "Yes"
`readability-isolate-declaration <readability-isolate-declaration.html>`_, "Yes"
`readability-magic-numbers <readability-magic-numbers.html>`_,
`readability-make-member-function-const <readability-make-member-function-const.html>`_, "Yes"
`readability-misleading-indentation <readability-misleading-indentation.html>`_,
`readability-misplaced-array-index <readability-misplaced-array-index.html>`_, "Yes"
`readability-named-parameter <readability-named-parameter.html>`_, "Yes"
`readability-non-const-parameter <readability-non-const-parameter.html>`_, "Yes"
`readability-qualified-auto <readability-qualified-auto.html>`_, "Yes"
`readability-redundant-access-specifiers <readability-redundant-access-specifiers.html>`_, "Yes"
`readability-redundant-control-flow <readability-redundant-control-flow.html>`_, "Yes"
`readability-redundant-declaration <readability-redundant-declaration.html>`_, "Yes"
`readability-redundant-function-ptr-dereference <readability-redundant-function-ptr-dereference.html>`_, "Yes"
`readability-redundant-member-init <readability-redundant-member-init.html>`_, "Yes"
`readability-redundant-preprocessor <readability-redundant-preprocessor.html>`_,
`readability-redundant-smartptr-get <readability-redundant-smartptr-get.html>`_, "Yes"
`readability-redundant-string-cstr <readability-redundant-string-cstr.html>`_, "Yes"
`readability-redundant-string-init <readability-redundant-string-init.html>`_, "Yes"
`readability-simplify-boolean-expr <readability-simplify-boolean-expr.html>`_, "Yes"
`readability-simplify-subscript-expr <readability-simplify-subscript-expr.html>`_, "Yes"
`readability-static-accessed-through-instance <readability-static-accessed-through-instance.html>`_, "Yes"
`readability-static-definition-in-anonymous-namespace <readability-static-definition-in-anonymous-namespace.html>`_, "Yes"
`readability-string-compare <readability-string-compare.html>`_, "Yes"
`readability-uniqueptr-delete-release <readability-uniqueptr-delete-release.html>`_, "Yes"
`readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_, "Yes"
`readability-use-anyofallof <readability-use-anyofallof.html>`_,
`zircon-temporary-objects <zircon-temporary-objects.html>`_,
.. csv-table:: Aliases..
:header: "Name", "Redirect", "Offers fixes"
`cert-con36-c <cert-con36-c.html>`_, `bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_,
`cert-con54-cpp <cert-con54-cpp.html>`_, `bugprone-spuriously-wake-up-functions <bugprone-spuriously-wake-up-functions.html>`_,
`cert-dcl03-c <cert-dcl03-c.html>`_, `misc-static-assert <misc-static-assert.html>`_, "Yes"
`cert-dcl16-c <cert-dcl16-c.html>`_, `readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_, "Yes"
`cert-dcl37-c <cert-dcl37-c.html>`_, `bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_, "Yes"
`cert-dcl51-cpp <cert-dcl51-cpp.html>`_, `bugprone-reserved-identifier <bugprone-reserved-identifier.html>`_, "Yes"
`cert-dcl54-cpp <cert-dcl54-cpp.html>`_, `misc-new-delete-overloads <misc-new-delete-overloads.html>`_,
`cert-dcl59-cpp <cert-dcl59-cpp.html>`_, `google-build-namespaces <google-build-namespaces.html>`_,
`cert-err09-cpp <cert-err09-cpp.html>`_, `misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_,
`cert-err61-cpp <cert-err61-cpp.html>`_, `misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_,
`cert-fio38-c <cert-fio38-c.html>`_, `misc-non-copyable-objects <misc-non-copyable-objects.html>`_,
`cert-msc30-c <cert-msc30-c.html>`_, `cert-msc50-cpp <cert-msc50-cpp.html>`_,
`cert-msc32-c <cert-msc32-c.html>`_, `cert-msc51-cpp <cert-msc51-cpp.html>`_,
`cert-oop11-cpp <cert-oop11-cpp.html>`_, `performance-move-constructor-init <performance-move-constructor-init.html>`_,
`cert-oop54-cpp <cert-oop54-cpp.html>`_, `bugprone-unhandled-self-assignment <bugprone-unhandled-self-assignment.html>`_,
`cert-pos44-c <cert-pos44-c.html>`_, `bugprone-bad-signal-to-kill-thread <bugprone-bad-signal-to-kill-thread.html>`_,
`cert-pos47-c <cert-pos47-c.html>`_, `concurrency-thread-canceltype-asynchronous <concurrency-thread-canceltype-asynchronous.html>`_,
`cert-sig30-c <cert-sig30-c.html>`_, `bugprone-signal-handler <bugprone-signal-handler.html>`_,
`cert-str34-c <cert-str34-c.html>`_, `bugprone-signed-char-misuse <bugprone-signed-char-misuse.html>`_,
`clang-analyzer-core.CallAndMessage <clang-analyzer-core.CallAndMessage.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.DivideZero <clang-analyzer-core.DivideZero.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.NonNullParamChecker <clang-analyzer-core.NonNullParamChecker.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.NullDereference <clang-analyzer-core.NullDereference.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.StackAddressEscape <clang-analyzer-core.StackAddressEscape.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.UndefinedBinaryOperatorResult <clang-analyzer-core.UndefinedBinaryOperatorResult.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.VLASize <clang-analyzer-core.VLASize.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.uninitialized.ArraySubscript <clang-analyzer-core.uninitialized.ArraySubscript.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.uninitialized.Assign <clang-analyzer-core.uninitialized.Assign.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.uninitialized.Branch <clang-analyzer-core.uninitialized.Branch.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-core.uninitialized.UndefReturn <clang-analyzer-core.uninitialized.UndefReturn.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-cplusplus.Move <clang-analyzer-cplusplus.Move.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-cplusplus.NewDelete <clang-analyzer-cplusplus.NewDelete.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-cplusplus.NewDeleteLeaks <clang-analyzer-cplusplus.NewDeleteLeaks.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-deadcode.DeadStores <clang-analyzer-deadcode.DeadStores.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-nullability.NullPassedToNonnull <clang-analyzer-nullability.NullPassedToNonnull.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-nullability.NullReturnedFromNonnull <clang-analyzer-nullability.NullReturnedFromNonnull.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-nullability.NullableDereferenced <clang-analyzer-nullability.NullableDereferenced.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-nullability.NullablePassedToNonnull <clang-analyzer-nullability.NullablePassedToNonnull.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.cplusplus.UninitializedObject <clang-analyzer-optin.cplusplus.UninitializedObject.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.cplusplus.VirtualCall <clang-analyzer-optin.cplusplus.VirtualCall.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.mpi.MPI-Checker <clang-analyzer-optin.mpi.MPI-Checker.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker <clang-analyzer-optin.osx.cocoa.localizability.EmptyLocalizationContextChecker.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker <clang-analyzer-optin.osx.cocoa.localizability.NonLocalizedStringChecker.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.API <clang-analyzer-osx.API.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.SecKeychainAPI <clang-analyzer-osx.SecKeychainAPI.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.AtSync <clang-analyzer-osx.cocoa.AtSync.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.ClassRelease <clang-analyzer-osx.cocoa.ClassRelease.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.Dealloc <clang-analyzer-osx.cocoa.Dealloc.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.IncompatibleMethodTypes <clang-analyzer-osx.cocoa.IncompatibleMethodTypes.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.NSAutoreleasePool <clang-analyzer-osx.cocoa.NSAutoreleasePool.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.NSError <clang-analyzer-osx.cocoa.NSError.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.NilArg <clang-analyzer-osx.cocoa.NilArg.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.ObjCGenerics <clang-analyzer-osx.cocoa.ObjCGenerics.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.RetainCount <clang-analyzer-osx.cocoa.RetainCount.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.SelfInit <clang-analyzer-osx.cocoa.SelfInit.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.SuperDealloc <clang-analyzer-osx.cocoa.SuperDealloc.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.UnusedIvars <clang-analyzer-osx.cocoa.UnusedIvars.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.cocoa.VariadicMethodTypes <clang-analyzer-osx.cocoa.VariadicMethodTypes.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.CFError <clang-analyzer-osx.coreFoundation.CFError.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.CFNumber <clang-analyzer-osx.coreFoundation.CFNumber.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.CFRetainRelease <clang-analyzer-osx.coreFoundation.CFRetainRelease.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.containers.OutOfBounds <clang-analyzer-osx.coreFoundation.containers.OutOfBounds.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-osx.coreFoundation.containers.PointerSizedValues <clang-analyzer-osx.coreFoundation.containers.PointerSizedValues.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.FloatLoopCounter <clang-analyzer-security.FloatLoopCounter.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling <clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.UncheckedReturn <clang-analyzer-security.insecureAPI.UncheckedReturn.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.bcmp <clang-analyzer-security.insecureAPI.bcmp.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.bcopy <clang-analyzer-security.insecureAPI.bcopy.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.bzero <clang-analyzer-security.insecureAPI.bzero.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.getpw <clang-analyzer-security.insecureAPI.getpw.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.gets <clang-analyzer-security.insecureAPI.gets.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.mkstemp <clang-analyzer-security.insecureAPI.mkstemp.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.mktemp <clang-analyzer-security.insecureAPI.mktemp.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.rand <clang-analyzer-security.insecureAPI.rand.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.strcpy <clang-analyzer-security.insecureAPI.strcpy.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-security.insecureAPI.vfork <clang-analyzer-security.insecureAPI.vfork.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.API <clang-analyzer-unix.API.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.Malloc <clang-analyzer-unix.Malloc.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.MallocSizeof <clang-analyzer-unix.MallocSizeof.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.MismatchedDeallocator <clang-analyzer-unix.MismatchedDeallocator.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.Vfork <clang-analyzer-unix.Vfork.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.cstring.BadSizeArg <clang-analyzer-unix.cstring.BadSizeArg.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`clang-analyzer-unix.cstring.NullArg <clang-analyzer-unix.cstring.NullArg.html>`_, `Clang Static Analyzer <https://clang.llvm.org/docs/analyzer/checkers.html>`_,
`cppcoreguidelines-avoid-c-arrays <cppcoreguidelines-avoid-c-arrays.html>`_, `modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_,
`cppcoreguidelines-avoid-magic-numbers <cppcoreguidelines-avoid-magic-numbers.html>`_, `readability-magic-numbers <readability-magic-numbers.html>`_,
`cppcoreguidelines-c-copy-assignment-signature <cppcoreguidelines-c-copy-assignment-signature.html>`_, `misc-unconventional-assign-operator <misc-unconventional-assign-operator.html>`_,
`cppcoreguidelines-explicit-virtual-functions <cppcoreguidelines-explicit-virtual-functions.html>`_, `modernize-use-override <modernize-use-override.html>`_, "Yes"
`cppcoreguidelines-non-private-member-variables-in-classes <cppcoreguidelines-non-private-member-variables-in-classes.html>`_, `misc-non-private-member-variables-in-classes <misc-non-private-member-variables-in-classes.html>`_,
`fuchsia-header-anon-namespaces <fuchsia-header-anon-namespaces.html>`_, `google-build-namespaces <google-build-namespaces.html>`_,
`google-readability-braces-around-statements <google-readability-braces-around-statements.html>`_, `readability-braces-around-statements <readability-braces-around-statements.html>`_, "Yes"
`google-readability-function-size <google-readability-function-size.html>`_, `readability-function-size <readability-function-size.html>`_,
`google-readability-namespace-comments <google-readability-namespace-comments.html>`_, `llvm-namespace-comment <llvm-namespace-comment.html>`_,
`hicpp-avoid-c-arrays <hicpp-avoid-c-arrays.html>`_, `modernize-avoid-c-arrays <modernize-avoid-c-arrays.html>`_,
`hicpp-braces-around-statements <hicpp-braces-around-statements.html>`_, `readability-braces-around-statements <readability-braces-around-statements.html>`_, "Yes"
`hicpp-deprecated-headers <hicpp-deprecated-headers.html>`_, `modernize-deprecated-headers <modernize-deprecated-headers.html>`_, "Yes"
`hicpp-explicit-conversions <hicpp-explicit-conversions.html>`_, `google-explicit-constructor <google-explicit-constructor.html>`_, "Yes"
`hicpp-function-size <hicpp-function-size.html>`_, `readability-function-size <readability-function-size.html>`_,
`hicpp-invalid-access-moved <hicpp-invalid-access-moved.html>`_, `bugprone-use-after-move <bugprone-use-after-move.html>`_,
`hicpp-member-init <hicpp-member-init.html>`_, `cppcoreguidelines-pro-type-member-init <cppcoreguidelines-pro-type-member-init.html>`_, "Yes"
`hicpp-move-const-arg <hicpp-move-const-arg.html>`_, `performance-move-const-arg <performance-move-const-arg.html>`_, "Yes"
`hicpp-named-parameter <hicpp-named-parameter.html>`_, `readability-named-parameter <readability-named-parameter.html>`_, "Yes"
`hicpp-new-delete-operators <hicpp-new-delete-operators.html>`_, `misc-new-delete-overloads <misc-new-delete-overloads.html>`_,
`hicpp-no-array-decay <hicpp-no-array-decay.html>`_, `cppcoreguidelines-pro-bounds-array-to-pointer-decay <cppcoreguidelines-pro-bounds-array-to-pointer-decay.html>`_,
`hicpp-no-malloc <hicpp-no-malloc.html>`_, `cppcoreguidelines-no-malloc <cppcoreguidelines-no-malloc.html>`_,
`hicpp-noexcept-move <hicpp-noexcept-move.html>`_, `performance-noexcept-move-constructor <performance-noexcept-move-constructor.html>`_, "Yes"
`hicpp-special-member-functions <hicpp-special-member-functions.html>`_, `cppcoreguidelines-special-member-functions <cppcoreguidelines-special-member-functions.html>`_,
`hicpp-static-assert <hicpp-static-assert.html>`_, `misc-static-assert <misc-static-assert.html>`_, "Yes"
`hicpp-undelegated-constructor <hicpp-undelegated-constructor.html>`_, `bugprone-undelegated-constructor <bugprone-undelegated-constructor.html>`_,
`hicpp-uppercase-literal-suffix <hicpp-uppercase-literal-suffix.html>`_, `readability-uppercase-literal-suffix <readability-uppercase-literal-suffix.html>`_, "Yes"
`hicpp-use-auto <hicpp-use-auto.html>`_, `modernize-use-auto <modernize-use-auto.html>`_, "Yes"
`hicpp-use-emplace <hicpp-use-emplace.html>`_, `modernize-use-emplace <modernize-use-emplace.html>`_, "Yes"
`hicpp-use-equals-default <hicpp-use-equals-default.html>`_, `modernize-use-equals-default <modernize-use-equals-default.html>`_, "Yes"
`hicpp-use-equals-delete <hicpp-use-equals-delete.html>`_, `modernize-use-equals-delete <modernize-use-equals-delete.html>`_, "Yes"
`hicpp-use-noexcept <hicpp-use-noexcept.html>`_, `modernize-use-noexcept <modernize-use-noexcept.html>`_, "Yes"
`hicpp-use-nullptr <hicpp-use-nullptr.html>`_, `modernize-use-nullptr <modernize-use-nullptr.html>`_, "Yes"
`hicpp-use-override <hicpp-use-override.html>`_, `modernize-use-override <modernize-use-override.html>`_, "Yes"
`hicpp-vararg <hicpp-vararg.html>`_, `cppcoreguidelines-pro-type-vararg <cppcoreguidelines-pro-type-vararg.html>`_,
`llvm-else-after-return <llvm-else-after-return.html>`_, `readability-else-after-return <readability-else-after-return.html>`_, "Yes"
`llvm-qualified-auto <llvm-qualified-auto.html>`_, `readability-qualified-auto <readability-qualified-auto.html>`_, "Yes"
.. title:: clang-tidy - llvm-else-after-return
.. meta::
:http-equiv=refresh: 5;URL=readability-else-after-return.html
llvm-else-after-return
======================
The llvm-else-after-return check is an alias, please see
`readability-else-after-return <readability-else-after-return.html>`_
for more information.
.. title:: clang-tidy - llvm-header-guard
llvm-header-guard
=================
Finds and fixes header guards that do not adhere to LLVM style.
Options
-------
.. option:: HeaderFileExtensions
A comma-separated list of filename extensions of header files (the filename
extensions should not include "." prefix). Default is "h,hh,hpp,hxx".
For header files without an extension, use an empty string (if there are no
other desired extensions) or leave an empty element in the list. e.g.,
"h,hh,hpp,hxx," (note the trailing comma).
.. title:: clang-tidy - llvm-include-order
llvm-include-order
==================
Checks the correct order of ``#includes``.
See https://llvm.org/docs/CodingStandards.html#include-style
.. title:: clang-tidy - llvm-namespace-comment
llvm-namespace-comment
======================
`google-readability-namespace-comments` redirects here as an alias for this
check.
Checks that long namespaces have a closing comment.
https://llvm.org/docs/CodingStandards.html#namespace-indentation
https://google.github.io/styleguide/cppguide.html#Namespaces
.. code-block:: c++
namespace n1 {
void f();
}
// becomes
namespace n1 {
void f();
} // namespace n1
Options
-------
.. option:: ShortNamespaceLines
Requires the closing brace of the namespace definition to be followed by a
closing comment if the body of the namespace has more than
`ShortNamespaceLines` lines of code. The value is an unsigned integer that
defaults to `1U`.
.. option:: SpacesBeforeComments
An unsigned integer specifying the number of spaces before the comment
closing a namespace definition. Default is `1U`.
.. title:: clang-tidy - llvm-prefer-isa-or-dyn-cast-in-conditionals
llvm-prefer-isa-or-dyn-cast-in-conditionals
===========================================
Looks at conditionals and finds and replaces cases of ``cast<>``,
which will assert rather than return a null pointer, and
``dyn_cast<>`` where the return value is not captured. Additionally,
finds and replaces cases that match the pattern ``var &&
isa<X>(var)``, where ``var`` is evaluated twice.
.. code-block:: c++
// Finds these:
if (auto x = cast<X>(y)) {}
// is replaced by:
if (auto x = dyn_cast<X>(y)) {}
if (cast<X>(y)) {}
// is replaced by:
if (isa<X>(y)) {}
if (dyn_cast<X>(y)) {}
// is replaced by:
if (isa<X>(y)) {}
if (var && isa<T>(var)) {}
// is replaced by:
if (isa_and_nonnull<T>(var.foo())) {}
// Other cases are ignored, e.g.:
if (auto f = cast<Z>(y)->foo()) {}
if (cast<Z>(y)->foo()) {}
if (X.cast(y)) {}
.. title:: clang-tidy - llvm-prefer-register-over-unsigned
llvm-prefer-register-over-unsigned
==================================
Finds historical use of ``unsigned`` to hold vregs and physregs and rewrites
them to use ``Register``.
Currently this works by finding all variables of unsigned integer type whose
initializer begins with an implicit cast from ``Register`` to ``unsigned``.
.. code-block:: c++
void example(MachineOperand &MO) {
unsigned Reg = MO.getReg();
...
}
becomes:
.. code-block:: c++
void example(MachineOperand &MO) {
Register Reg = MO.getReg();
...
}
.. title:: clang-tidy - llvm-qualified-auto
.. meta::
:http-equiv=refresh: 5;URL=readability-qualified-auto.html
llvm-qualified-auto
===================
The llvm-qualified-auto check is an alias, please see
`readability-qualified-auto <readability-qualified-auto.html>`_
for more information.
.. title:: clang-tidy - llvm-twine-local
llvm-twine-local
================
Looks for local ``Twine`` variables which are prone to use after frees and
should be generally avoided.
.. code-block:: c++
static Twine Moo = Twine("bark") + "bah";
// becomes
static std::string Moo = (Twine("bark") + "bah").str();
.. title:: clang-tidy - llvmlibc-callee-namespace
llvmlibc-callee-namespace
====================================
Checks all calls resolve to functions within ``__llvm_libc`` namespace.
.. code-block:: c++
namespace __llvm_libc {
// Allow calls with the fully qualified name.
__llvm_libc::strlen("hello");
// Allow calls to compiler provided functions.
(void)__builtin_abs(-1);
// Bare calls are allowed as long as they resolve to the correct namespace.
strlen("world");
// Disallow calling into functions in the global namespace.
::strlen("!");
} // namespace __llvm_libc
.. title:: clang-tidy - llvmlibc-implementation-in-namespace
llvmlibc-implementation-in-namespace
====================================
Checks that all declarations in the llvm-libc implementation are within the
correct namespace.
.. code-block:: c++
// Correct: implementation inside the correct namespace.
namespace __llvm_libc {
void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
// Namespaces within __llvm_libc namespace are allowed.
namespace inner{
int localVar = 0;
}
// Functions with C linkage are allowed.
extern "C" void str_fuzz(){}
}
// Incorrect: implementation not in a namespace.
void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
// Incorrect: outer most namespace is not correct.
namespace something_else {
void LLVM_LIBC_ENTRYPOINT(strcpy)(char *dest, const char *src) {}
}
.. title:: clang-tidy - llvmlibc-restrict-system-libc-headers
llvmlibc-restrict-system-libc-headers
=====================================
Finds includes of system libc headers not provided by the compiler within
llvm-libc implementations.
.. code-block:: c++
#include <stdio.h> // Not allowed because it is part of system libc.
#include <stddef.h> // Allowed because it is provided by the compiler.
#include "internal/stdio.h" // Allowed because it is NOT part of system libc.
This check is necessary because accidentally including system libc headers can
lead to subtle and hard to detect bugs. For example consider a system libc
whose ``dirent`` struct has slightly different field ordering than llvm-libc.
While this will compile successfully, this can cause issues during runtime
because they are ABI incompatible.
Options
-------
.. option:: Includes
A string containing a comma separated glob list of allowed include
filenames. Similar to the -checks glob list for running clang-tidy itself,
the two wildcard characters are `*` and `-`, to include and exclude globs,
respectively. The default is `-*`, which disallows all includes.
This can be used to allow known safe includes such as Linux development
headers. See :doc:`portability-restrict-system-includes
<portability-restrict-system-includes>` for more
details.
.. title:: clang-tidy - misc-definitions-in-headers
misc-definitions-in-headers
===========================
Finds non-extern non-inline function and variable definitions in header files,
which can lead to potential ODR violations in case these headers are included
from multiple translation units.
.. code-block:: c++
// Foo.h
int a = 1; // Warning: variable definition.
extern int d; // OK: extern variable.
namespace N {
int e = 2; // Warning: variable definition.
}
// Warning: variable definition.
const char* str = "foo";
// OK: internal linkage variable definitions are ignored for now.
// Although these might also cause ODR violations, we can be less certain and
// should try to keep the false-positive rate down.
static int b = 1;
const int c = 1;
const char* const str2 = "foo";
constexpr int k = 1;
// Warning: function definition.
int g() {
return 1;
}
// OK: inline function definition is allowed to be defined multiple times.
inline int e() {
return 1;
}
class A {
public:
int f1() { return 1; } // OK: implicitly inline member function definition is allowed.
int f2();
static int d;
};
// Warning: not an inline member function definition.
int A::f2() { return 1; }
// OK: class static data member declaration is allowed.
int A::d = 1;
// OK: function template is allowed.
template<typename T>
T f3() {
T a = 1;
return a;
}
// Warning: full specialization of a function template is not allowed.
template <>
int f3() {
int a = 1;
return a;
}
template <typename T>
struct B {
void f1();
};
// OK: member function definition of a class template is allowed.
template <typename T>
void B<T>::f1() {}
class CE {
constexpr static int i = 5; // OK: inline variable definition.
};
inline int i = 5; // OK: inline variable definition.
constexpr int f10() { return 0; } // OK: constexpr function implies inline.
// OK: C++14 variable templates are inline.
template <class T>
constexpr T pi = T(3.1415926L);
Options
-------
.. option:: HeaderFileExtensions
A comma-separated list of filename extensions of header files (the filename
extensions should not include "." prefix). Default is "h,hh,hpp,hxx".
For header files without an extension, use an empty string (if there are no
other desired extensions) or leave an empty element in the list. e.g.,
"h,hh,hpp,hxx," (note the trailing comma).
.. option:: UseHeaderFileExtension
When `true`, the check will use the file extension to distinguish header
files. Default is `true`.
.. title:: clang-tidy - misc-misplaced-const
misc-misplaced-const
====================
This check diagnoses when a ``const`` qualifier is applied to a ``typedef``/
``using`` to a pointer type rather than to the pointee, because such constructs
are often misleading to developers because the ``const`` applies to the pointer
rather than the pointee.
For instance, in the following code, the resulting type is ``int * const``
rather than ``const int *``:
.. code-block:: c++
typedef int *int_ptr;
void f(const int_ptr ptr) {
*ptr = 0; // potentially quite unexpectedly the int can be modified here
ptr = 0; // does not compile
}
The check does not diagnose when the underlying ``typedef``/``using`` type is a
pointer to a ``const`` type or a function pointer type. This is because the
``const`` qualifier is less likely to be mistaken because it would be redundant
(or disallowed) on the underlying pointee type.
.. title:: clang-tidy - misc-new-delete-overloads
misc-new-delete-overloads
=========================
`cert-dcl54-cpp` redirects here as an alias for this check.
The check flags overloaded operator ``new()`` and operator ``delete()``
functions that do not have a corresponding free store function defined within
the same scope.
For instance, the check will flag a class implementation of a non-placement
operator ``new()`` when the class does not also define a non-placement operator
``delete()`` function as well.
The check does not flag implicitly-defined operators, deleted or private
operators, or placement operators.
This check corresponds to CERT C++ Coding Standard rule `DCL54-CPP. Overload allocation and deallocation functions as a pair in the same scope
<https://www.securecoding.cert.org/confluence/display/cplusplus/DCL54-CPP.+Overload+allocation+and+deallocation+functions+as+a+pair+in+the+same+scope>`_.
.. title:: clang-tidy - misc-no-recursion
misc-no-recursion
=================
Finds strongly connected functions (by analyzing the call graph for
SCC's (Strongly Connected Components) that are loops),
diagnoses each function in the cycle,
and displays one example of a possible call graph loop (recursion).
References:
* CERT C++ Coding Standard rule `DCL56-CPP. Avoid cycles during initialization of static objects <https://wiki.sei.cmu.edu/confluence/display/cplusplus/DCL56-CPP.+Avoid+cycles+during+initialization+of+static+objects>`_.
* JPL Institutional Coding Standard for the C Programming Language (JPL DOCID D-60411) rule `2.4 Do not use direct or indirect recursion`.
* OpenCL Specification, Version 1.2 rule `6.9 Restrictions: i. Recursion is not supported. <https://www.khronos.org/registry/OpenCL/specs/opencl-1.2.pdf>`_.
Limitations:
* The check does not handle calls done through function pointers
* The check does not handle C++ destructors
.. title:: clang-tidy - misc-non-copyable-objects
misc-non-copyable-objects
=========================
`cert-fio38-c` redirects here as an alias for this check.
The check flags dereferences and non-pointer declarations of objects that are
not meant to be passed by value, such as C FILE objects or POSIX
``pthread_mutex_t`` objects.
This check corresponds to CERT C++ Coding Standard rule `FIO38-C. Do not copy a FILE object
<https://www.securecoding.cert.org/confluence/display/c/FIO38-C.+Do+not+copy+a+FILE+object>`_.
.. title:: clang-tidy - misc-non-private-member-variables-in-classes
misc-non-private-member-variables-in-classes
============================================
`cppcoreguidelines-non-private-member-variables-in-classes` redirects here
as an alias for this check.
Finds classes that contain non-static data members in addition to user-declared
non-static member functions and diagnose all data members declared with a
non-``public`` access specifier. The data members should be declared as
``private`` and accessed through member functions instead of exposed to derived
classes or class consumers.
Options
-------
.. option:: IgnoreClassesWithAllMemberVariablesBeingPublic
Allows to completely ignore classes if **all** the member variables in that
class a declared with a ``public`` access specifier.
.. option:: IgnorePublicMemberVariables
Allows to ignore (not diagnose) **all** the member variables declared with
a ``public`` access specifier.
.. title:: clang-tidy - misc-redundant-expression
misc-redundant-expression
=========================
Detect redundant expressions which are typically errors due to copy-paste.
Depending on the operator expressions may be
- redundant,
- always ``true``,
- always ``false``,
- always a constant (zero or one).
Examples:
.. code-block:: c++
((x+1) | (x+1)) // (x+1) is redundant
(p->x == p->x) // always true
(p->x < p->x) // always false
(speed - speed + 1 == 12) // speed - speed is always zero
.. title:: clang-tidy - misc-static-assert
misc-static-assert
==================
`cert-dcl03-c` redirects here as an alias for this check.
Replaces ``assert()`` with ``static_assert()`` if the condition is evaluatable
at compile time.
The condition of ``static_assert()`` is evaluated at compile time which is
safer and more efficient.
.. title:: clang-tidy - misc-throw-by-value-catch-by-reference
misc-throw-by-value-catch-by-reference
======================================
`cert-err09-cpp` redirects here as an alias for this check.
`cert-err61-cpp` redirects here as an alias for this check.
Finds violations of the rule "Throw by value, catch by reference" presented for
example in "C++ Coding Standards" by H. Sutter and A. Alexandrescu, as well as
the CERT C++ Coding Standard rule `ERR61-CPP. Catch exceptions by lvalue reference
<https://wiki.sei.cmu.edu/confluence/display/cplusplus/ERR61-CPP.+Catch+exceptions+by+lvalue+reference>`_.
Exceptions:
* Throwing string literals will not be flagged despite being a pointer. They
are not susceptible to slicing and the usage of string literals is idomatic.
* Catching character pointers (``char``, ``wchar_t``, unicode character types)
will not be flagged to allow catching sting literals.
* Moved named values will not be flagged as not throwing an anonymous
temporary. In this case we can be sure that the user knows that the object
can't be accessed outside catch blocks handling the error.
* Throwing function parameters will not be flagged as not throwing an
anonymous temporary. This allows helper functions for throwing.
* Re-throwing caught exception variables will not be flragged as not throwing
an anonymous temporary. Although this can usually be done by just writing
``throw;`` it happens often enough in real code.
Options
-------
.. option:: CheckThrowTemporaries
Triggers detection of violations of the CERT recommendation ERR09-CPP. Throw
anonymous temporaries.
Default is `true`.
.. option:: WarnOnLargeObject
Also warns for any large, trivial object caught by value. Catching a large
object by value is not dangerous but affects the performance negatively. The
maximum size of an object allowed to be caught without warning can be set
using the `MaxSize` option.
Default is `false`.
.. option:: MaxSize
Determines the maximum size of an object allowed to be caught without
warning. Only applicable if :option:`WarnOnLargeObject` is set to `true`. If
the option is set by the user to `std::numeric_limits<uint64_t>::max()` then
it reverts to the default value.
Default is the size of `size_t`.
.. title:: clang-tidy - misc-unconventional-assign-operator
misc-unconventional-assign-operator
===================================
Finds declarations of assign operators with the wrong return and/or argument
types and definitions with good return type but wrong ``return`` statements.
* The return type must be ``Class&``.
* Works with move-assign and assign by value.
* Private and deleted operators are ignored.
* The operator must always return ``*this``.
.. title:: clang-tidy - misc-uniqueptr-reset-release
misc-uniqueptr-reset-release
============================
Find and replace ``unique_ptr::reset(release())`` with ``std::move()``.
Example:
.. code-block:: c++
std::unique_ptr<Foo> x, y;
x.reset(y.release()); -> x = std::move(y);
If ``y`` is already rvalue, ``std::move()`` is not added. ``x`` and ``y`` can
also be ``std::unique_ptr<Foo>*``.
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. title:: clang-tidy - misc-unused-alias-decls
misc-unused-alias-decls
=======================
Finds unused namespace alias declarations.
.. code-block:: c++
namespace my_namespace {
class C {};
}
namespace unused_alias = ::my_namespace;
.. title:: clang-tidy - misc-unused-parameters
misc-unused-parameters
======================
Finds unused function parameters. Unused parameters may signify a bug in the
code (e.g. when a different parameter is used instead). The suggested fixes
either comment parameter name out or remove the parameter completely, if all
callers of the function are in the same translation unit and can be updated.
The check is similar to the ``-Wunused-parameter`` compiler diagnostic and can be
used to prepare a codebase to enabling of that diagnostic. By default the check
is more permissive (see :option:`StrictMode`).
.. code-block:: c++
void a(int i) { /*some code that doesn't use `i`*/ }
// becomes
void a(int /*i*/) { /*some code that doesn't use `i`*/ }
.. code-block:: c++
static void staticFunctionA(int i);
static void staticFunctionA(int i) { /*some code that doesn't use `i`*/ }
// becomes
static void staticFunctionA()
static void staticFunctionA() { /*some code that doesn't use `i`*/ }
Options
-------
.. option:: StrictMode
When `false` (default value), the check will ignore trivially unused parameters,
i.e. when the corresponding function has an empty body (and in case of
constructors - no constructor initializers). When the function body is empty,
an unused parameter is unlikely to be unnoticed by a human reader, and
there's basically no place for a bug to hide.
.. title:: clang-tidy - misc-unused-using-decls
misc-unused-using-decls
=======================
Finds unused ``using`` declarations.
Example:
.. code-block:: c++
namespace n { class C; }
using n::C; // Never actually used.
.. title:: clang-tidy - modernize-avoid-bind
modernize-avoid-bind
====================
The check finds uses of ``std::bind`` and ``boost::bind`` and replaces them
with lambdas. Lambdas will use value-capture unless reference capture is
explicitly requested with ``std::ref`` or ``boost::ref``.
It supports arbitrary callables including member functions, function objects,
and free functions, and all variations thereof. Anything that you can pass
to the first argument of ``bind`` should be diagnosable. Currently, the only
known case where a fix-it is unsupported is when the same placeholder is
specified multiple times in the parameter list.
Given:
.. code-block:: c++
int add(int x, int y) { return x + y; }
Then:
.. code-block:: c++
void f() {
int x = 2;
auto clj = std::bind(add, x, _1);
}
is replaced by:
.. code-block:: c++
void f() {
int x = 2;
auto clj = [=](auto && arg1) { return add(x, arg1); };
}
``std::bind`` can be hard to read and can result in larger object files and
binaries due to type information that will not be produced by equivalent
lambdas.
Options
-------
.. option:: PermissiveParameterList
If the option is set to `true`, the check will append ``auto&&...`` to the end
of every placeholder parameter list. Without this, it is possible for a fix-it
to perform an incorrect transformation in the case where the result of the ``bind``
is used in the context of a type erased functor such as ``std::function`` which
allows mismatched arguments. For example:
.. code-block:: c++
int add(int x, int y) { return x + y; }
int foo() {
std::function<int(int,int)> ignore_args = std::bind(add, 2, 2);
return ignore_args(3, 3);
}
is valid code, and returns `4`. The actual values passed to ``ignore_args`` are
simply ignored. Without ``PermissiveParameterList``, this would be transformed into
.. code-block:: c++
int add(int x, int y) { return x + y; }
int foo() {
std::function<int(int,int)> ignore_args = [] { return add(2, 2); }
return ignore_args(3, 3);
}
which will *not* compile, since the lambda does not contain an ``operator()`` that
that accepts 2 arguments. With permissive parameter list, it instead generates
.. code-block:: c++
int add(int x, int y) { return x + y; }
int foo() {
std::function<int(int,int)> ignore_args = [](auto&&...) { return add(2, 2); }
return ignore_args(3, 3);
}
which is correct.
This check requires using C++14 or higher to run.
.. title:: clang-tidy - modernize-avoid-c-arrays
modernize-avoid-c-arrays
========================
`cppcoreguidelines-avoid-c-arrays` redirects here as an alias for this check.
`hicpp-avoid-c-arrays` redirects here as an alias for this check.
Finds C-style array types and recommend to use ``std::array<>`` /
``std::vector<>``. All types of C arrays are diagnosed.
However, fix-it are potentially dangerous in header files and are therefore not
emitted right now.
.. code:: c++
int a[] = {1, 2}; // warning: do not declare C-style arrays, use std::array<> instead
int b[1]; // warning: do not declare C-style arrays, use std::array<> instead
void foo() {
int c[b[0]]; // warning: do not declare C VLA arrays, use std::vector<> instead
}
template <typename T, int Size>
class array {
T d[Size]; // warning: do not declare C-style arrays, use std::array<> instead
int e[1]; // warning: do not declare C-style arrays, use std::array<> instead
};
array<int[4], 2> d; // warning: do not declare C-style arrays, use std::array<> instead
using k = int[4]; // warning: do not declare C-style arrays, use std::array<> instead
However, the ``extern "C"`` code is ignored, since it is common to share
such headers between C code, and C++ code.
.. code:: c++
// Some header
extern "C" {
int f[] = {1, 2}; // not diagnosed
int j[1]; // not diagnosed
inline void bar() {
{
int j[j[0]]; // not diagnosed
}
}
}
Similarly, the ``main()`` function is ignored. Its second and third parameters
can be either ``char* argv[]`` or ``char** argv``, but can not be
``std::array<>``.
.. title:: clang-tidy - modernize-concat-nested-namespaces
modernize-concat-nested-namespaces
==================================
Checks for use of nested namespaces such as ``namespace a { namespace b { ... } }``
and suggests changing to the more concise syntax introduced in C++17: ``namespace a::b { ... }``.
Inline namespaces are not modified.
For example:
.. code-block:: c++
namespace n1 {
namespace n2 {
void t();
}
}
namespace n3 {
namespace n4 {
namespace n5 {
void t();
}
}
namespace n6 {
namespace n7 {
void t();
}
}
}
Will be modified to:
.. code-block:: c++
namespace n1::n2 {
void t();
}
namespace n3 {
namespace n4::n5 {
void t();
}
namespace n6::n7 {
void t();
}
}
.. title:: clang-tidy - modernize-deprecated-headers
modernize-deprecated-headers
============================
Some headers from C library were deprecated in C++ and are no longer welcome in
C++ codebases. Some have no effect in C++. For more details refer to the C++ 14
Standard [depr.c.headers] section.
This check replaces C standard library headers with their C++ alternatives and
removes redundant ones.
Important note: the Standard doesn't guarantee that the C++ headers declare all
the same functions in the global namespace. The check in its current form can
break the code that uses library symbols from the global namespace.
* `<assert.h>`
* `<complex.h>`
* `<ctype.h>`
* `<errno.h>`
* `<fenv.h>` // deprecated since C++11
* `<float.h>`
* `<inttypes.h>`
* `<limits.h>`
* `<locale.h>`
* `<math.h>`
* `<setjmp.h>`
* `<signal.h>`
* `<stdarg.h>`
* `<stddef.h>`
* `<stdint.h>`
* `<stdio.h>`
* `<stdlib.h>`
* `<string.h>`
* `<tgmath.h>` // deprecated since C++11
* `<time.h>`
* `<uchar.h>` // deprecated since C++11
* `<wchar.h>`
* `<wctype.h>`
If the specified standard is older than C++11 the check will only replace
headers deprecated before C++11, otherwise -- every header that appeared in
the previous list.
These headers don't have effect in C++:
* `<iso646.h>`
* `<stdalign.h>`
* `<stdbool.h>`
.. title:: clang-tidy - modernize-deprecated-ios-base-aliases
modernize-deprecated-ios-base-aliases
=====================================
Detects usage of the deprecated member types of ``std::ios_base`` and replaces
those that have a non-deprecated equivalent.
=================================== ===========================
Deprecated member type Replacement
=================================== ===========================
``std::ios_base::io_state`` ``std::ios_base::iostate``
``std::ios_base::open_mode`` ``std::ios_base::openmode``
``std::ios_base::seek_dir`` ``std::ios_base::seekdir``
``std::ios_base::streamoff``
``std::ios_base::streampos``
=================================== ===========================
.. title:: clang-tidy - modernize-loop-convert
modernize-loop-convert
======================
This check converts ``for(...; ...; ...)`` loops to use the new range-based
loops in C++11.
Three kinds of loops can be converted:
- Loops over statically allocated arrays.
- Loops over containers, using iterators.
- Loops over array-like containers, using ``operator[]`` and ``at()``.
MinConfidence option
--------------------
risky
^^^^^
In loops where the container expression is more complex than just a
reference to a declared expression (a variable, function, enum, etc.),
and some part of it appears elsewhere in the loop, we lower our confidence
in the transformation due to the increased risk of changing semantics.
Transformations for these loops are marked as `risky`, and thus will only
be converted if the minimum required confidence level is set to `risky`.
.. code-block:: c++
int arr[10][20];
int l = 5;
for (int j = 0; j < 20; ++j)
int k = arr[l][j] + l; // using l outside arr[l] is considered risky
for (int i = 0; i < obj.getVector().size(); ++i)
obj.foo(10); // using 'obj' is considered risky
See
:ref:`Range-based loops evaluate end() only once<IncorrectRiskyTransformation>`
for an example of an incorrect transformation when the minimum required confidence
level is set to `risky`.
reasonable (Default)
^^^^^^^^^^^^^^^^^^^^
If a loop calls ``.end()`` or ``.size()`` after each iteration, the
transformation for that loop is marked as `reasonable`, and thus will
be converted if the required confidence level is set to `reasonable`
(default) or lower.
.. code-block:: c++
// using size() is considered reasonable
for (int i = 0; i < container.size(); ++i)
cout << container[i];
safe
^^^^
Any other loops that do not match the above criteria to be marked as
`risky` or `reasonable` are marked `safe`, and thus will be converted
if the required confidence level is set to `safe` or lower.
.. code-block:: c++
int arr[] = {1,2,3};
for (int i = 0; i < 3; ++i)
cout << arr[i];
Example
-------
Original:
.. code-block:: c++
const int N = 5;
int arr[] = {1,2,3,4,5};
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
// safe conversion
for (int i = 0; i < N; ++i)
cout << arr[i];
// reasonable conversion
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
cout << *it;
// reasonable conversion
for (int i = 0; i < v.size(); ++i)
cout << v[i];
After applying the check with minimum confidence level set to `reasonable` (default):
.. code-block:: c++
const int N = 5;
int arr[] = {1,2,3,4,5};
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
// safe conversion
for (auto & elem : arr)
cout << elem;
// reasonable conversion
for (auto & elem : v)
cout << elem;
// reasonable conversion
for (auto & elem : v)
cout << elem;
Reverse Iterator Support
------------------------
The converter is also capable of transforming iterator loops which use
``rbegin`` and ``rend`` for looping backwards over a container. Out of the box
this will automatically happen in C++20 mode using the ``ranges`` library,
however the check can be configured to work without C++20 by specifying a
function to reverse a range and optionally the header file where that function
lives.
.. option:: UseCxx20ReverseRanges
When set to true convert loops when in C++20 or later mode using
``std::ranges::reverse_view``.
Default value is ``true``.
.. option:: MakeReverseRangeFunction
Specify the function used to reverse an iterator pair, the function should
accept a class with ``rbegin`` and ``rend`` methods and return a
class with ``begin`` and ``end`` methods methods that call the ``rbegin`` and
``rend`` methods respectively. Common examples are ``ranges::reverse_view``
and ``llvm::reverse``.
Default value is an empty string.
.. option:: MakeReverseRangeHeader
Specifies the header file where :option:`MakeReverseRangeFunction` is
declared. For the previous examples this option would be set to
``range/v3/view/reverse.hpp`` and ``llvm/ADT/STLExtras.h`` respectively.
If this is an empty string and :option:`MakeReverseRangeFunction` is set,
the check will proceed on the assumption that the function is already
available in the translation unit.
This can be wrapped in angle brackets to signify to add the include as a
system include.
Default value is an empty string.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
Limitations
-----------
There are certain situations where the tool may erroneously perform
transformations that remove information and change semantics. Users of the tool
should be aware of the behaviour and limitations of the check outlined by
the cases below.
Comments inside loop headers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Comments inside the original loop header are ignored and deleted when
transformed.
.. code-block:: c++
for (int i = 0; i < N; /* This will be deleted */ ++i) { }
Range-based loops evaluate end() only once
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The C++11 range-based for loop calls ``.end()`` only once during the
initialization of the loop. If in the original loop ``.end()`` is called after
each iteration the semantics of the transformed loop may differ.
.. code-block:: c++
// The following is semantically equivalent to the C++11 range-based for loop,
// therefore the semantics of the header will not change.
for (iterator it = container.begin(), e = container.end(); it != e; ++it) { }
// Instead of calling .end() after each iteration, this loop will be
// transformed to call .end() only once during the initialization of the loop,
// which may affect semantics.
for (iterator it = container.begin(); it != container.end(); ++it) { }
.. _IncorrectRiskyTransformation:
As explained above, calling member functions of the container in the body
of the loop is considered `risky`. If the called member function modifies the
container the semantics of the converted loop will differ due to ``.end()``
being called only once.
.. code-block:: c++
bool flag = false;
for (vector<T>::iterator it = vec.begin(); it != vec.end(); ++it) {
// Add a copy of the first element to the end of the vector.
if (!flag) {
// This line makes this transformation 'risky'.
vec.push_back(*it);
flag = true;
}
cout << *it;
}
The original code above prints out the contents of the container including the
newly added element while the converted loop, shown below, will only print the
original contents and not the newly added element.
.. code-block:: c++
bool flag = false;
for (auto & elem : vec) {
// Add a copy of the first element to the end of the vector.
if (!flag) {
// This line makes this transformation 'risky'
vec.push_back(elem);
flag = true;
}
cout << elem;
}
Semantics will also be affected if ``.end()`` has side effects. For example, in
the case where calls to ``.end()`` are logged the semantics will change in the
transformed loop if ``.end()`` was originally called after each iteration.
.. code-block:: c++
iterator end() {
num_of_end_calls++;
return container.end();
}
Overloaded operator->() with side effects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Similarly, if ``operator->()`` was overloaded to have side effects, such as
logging, the semantics will change. If the iterator's ``operator->()`` was used
in the original loop it will be replaced with ``<container element>.<member>``
instead due to the implicit dereference as part of the range-based for loop.
Therefore any side effect of the overloaded ``operator->()`` will no longer be
performed.
.. code-block:: c++
for (iterator it = c.begin(); it != c.end(); ++it) {
it->func(); // Using operator->()
}
// Will be transformed to:
for (auto & elem : c) {
elem.func(); // No longer using operator->()
}
Pointers and references to containers
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
While most of the check's risk analysis is dedicated to determining whether
the iterator or container was modified within the loop, it is possible to
circumvent the analysis by accessing and modifying the container through a
pointer or reference.
If the container were directly used instead of using the pointer or reference
the following transformation would have only been applied at the `risky`
level since calling a member function of the container is considered `risky`.
The check cannot identify expressions associated with the container that are
different than the one used in the loop header, therefore the transformation
below ends up being performed at the `safe` level.
.. code-block:: c++
vector<int> vec;
vector<int> *ptr = &vec;
vector<int> &ref = vec;
for (vector<int>::iterator it = vec.begin(), e = vec.end(); it != e; ++it) {
if (!flag) {
// Accessing and modifying the container is considered risky, but the risk
// level is not raised here.
ptr->push_back(*it);
ref.push_back(*it);
flag = true;
}
}
OpenMP
^^^^^^
As range-based for loops are only available since OpenMP 5, this check should
not been used on code with a compatibility requirements of OpenMP prior to
version 5. It is **intentional** that this check does not make any attempts to
exclude incorrect diagnostics on OpenMP for loops prior to OpenMP 5.
To prevent this check to be applied (and to break) OpenMP for loops but still be
applied to non-OpenMP for loops the usage of ``NOLINT`` (see
:ref:`clang-tidy-nolint`) on the specific for loops is recommended.
.. title:: clang-tidy - modernize-make-shared
modernize-make-shared
=====================
This check finds the creation of ``std::shared_ptr`` objects by explicitly
calling the constructor and a ``new`` expression, and replaces it with a call
to ``std::make_shared``.
.. code-block:: c++
auto my_ptr = std::shared_ptr<MyPair>(new MyPair(1, 2));
// becomes
auto my_ptr = std::make_shared<MyPair>(1, 2);
This check also finds calls to ``std::shared_ptr::reset()`` with a ``new``
expression, and replaces it with a call to ``std::make_shared``.
.. code-block:: c++
my_ptr.reset(new MyPair(1, 2));
// becomes
my_ptr = std::make_shared<MyPair>(1, 2);
Options
-------
.. option:: MakeSmartPtrFunction
A string specifying the name of make-shared-ptr function. Default is
`std::make_shared`.
.. option:: MakeSmartPtrFunctionHeader
A string specifying the corresponding header of make-shared-ptr function.
Default is `memory`.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. option:: IgnoreDefaultInitialization
If set to non-zero, the check does not suggest edits that will transform
default initialization into value initialization, as this can cause
performance regressions. Default is `1`.
.. title:: clang-tidy - modernize-make-unique
modernize-make-unique
=====================
This check finds the creation of ``std::unique_ptr`` objects by explicitly
calling the constructor and a ``new`` expression, and replaces it with a call
to ``std::make_unique``, introduced in C++14.
.. code-block:: c++
auto my_ptr = std::unique_ptr<MyPair>(new MyPair(1, 2));
// becomes
auto my_ptr = std::make_unique<MyPair>(1, 2);
This check also finds calls to ``std::unique_ptr::reset()`` with a ``new``
expression, and replaces it with a call to ``std::make_unique``.
.. code-block:: c++
my_ptr.reset(new MyPair(1, 2));
// becomes
my_ptr = std::make_unique<MyPair>(1, 2);
Options
-------
.. option:: MakeSmartPtrFunction
A string specifying the name of make-unique-ptr function. Default is
`std::make_unique`.
.. option:: MakeSmartPtrFunctionHeader
A string specifying the corresponding header of make-unique-ptr function.
Default is `<memory>`.
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. option:: IgnoreDefaultInitialization
If set to non-zero, the check does not suggest edits that will transform
default initialization into value initialization, as this can cause
performance regressions. Default is `1`.
.. title:: clang-tidy - modernize-pass-by-value
modernize-pass-by-value
=======================
With move semantics added to the language and the standard library updated with
move constructors added for many types it is now interesting to take an
argument directly by value, instead of by const-reference, and then copy. This
check allows the compiler to take care of choosing the best way to construct
the copy.
The transformation is usually beneficial when the calling code passes an
*rvalue* and assumes the move construction is a cheap operation. This short
example illustrates how the construction of the value happens:
.. code-block:: c++
void foo(std::string s);
std::string get_str();
void f(const std::string &str) {
foo(str); // lvalue -> copy construction
foo(get_str()); // prvalue -> move construction
}
.. note::
Currently, only constructors are transformed to make use of pass-by-value.
Contributions that handle other situations are welcome!
Pass-by-value in constructors
-----------------------------
Replaces the uses of const-references constructor parameters that are copied
into class fields. The parameter is then moved with `std::move()`.
Since ``std::move()`` is a library function declared in `<utility>` it may be
necessary to add this include. The check will add the include directive when
necessary.
.. code-block:: c++
#include <string>
class Foo {
public:
- Foo(const std::string &Copied, const std::string &ReadOnly)
- : Copied(Copied), ReadOnly(ReadOnly)
+ Foo(std::string Copied, const std::string &ReadOnly)
+ : Copied(std::move(Copied)), ReadOnly(ReadOnly)
{}
private:
std::string Copied;
const std::string &ReadOnly;
};
std::string get_cwd();
void f(const std::string &Path) {
// The parameter corresponding to 'get_cwd()' is move-constructed. By
// using pass-by-value in the Foo constructor we managed to avoid a
// copy-construction.
Foo foo(get_cwd(), Path);
}
If the parameter is used more than once no transformation is performed since
moved objects have an undefined state. It means the following code will be left
untouched:
.. code-block:: c++
#include <string>
void pass(const std::string &S);
struct Foo {
Foo(const std::string &S) : Str(S) {
pass(S);
}
std::string Str;
};
Known limitations
^^^^^^^^^^^^^^^^^
A situation where the generated code can be wrong is when the object referenced
is modified before the assignment in the init-list through a "hidden" reference.
Example:
.. code-block:: c++
std::string s("foo");
struct Base {
Base() {
s = "bar";
}
};
struct Derived : Base {
- Derived(const std::string &S) : Field(S)
+ Derived(std::string S) : Field(std::move(S))
{ }
std::string Field;
};
void f() {
- Derived d(s); // d.Field holds "bar"
+ Derived d(s); // d.Field holds "foo"
}
Note about delayed template parsing
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When delayed template parsing is enabled, constructors part of templated
contexts; templated constructors, constructors in class templates, constructors
of inner classes of template classes, etc., are not transformed. Delayed
template parsing is enabled by default on Windows as a Microsoft extension:
`Clang Compiler User’s Manual - Microsoft extensions`_.
Delayed template parsing can be enabled using the `-fdelayed-template-parsing`
flag and disabled using `-fno-delayed-template-parsing`.
Example:
.. code-block:: c++
template <typename T> class C {
std::string S;
public:
= // using -fdelayed-template-parsing (default on Windows)
= C(const std::string &S) : S(S) {}
+ // using -fno-delayed-template-parsing (default on non-Windows systems)
+ C(std::string S) : S(std::move(S)) {}
};
.. _Clang Compiler User’s Manual - Microsoft extensions: https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
.. seealso::
For more information about the pass-by-value idiom, read: `Want Speed? Pass by Value`_.
.. _Want Speed? Pass by Value: https://web.archive.org/web/20140205194657/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: ValuesOnly
When `true`, the check only warns about copied parameters that are already
passed by value. Default is `false`.
.. title:: clang-tidy - modernize-raw-string-literal
modernize-raw-string-literal
============================
This check selectively replaces string literals containing escaped characters
with raw string literals.
Example:
.. code-blocK:: c++
const char *const Quotes{"embedded \"quotes\""};
const char *const Paragraph{"Line one.\nLine two.\nLine three.\n"};
const char *const SingleLine{"Single line.\n"};
const char *const TrailingSpace{"Look here -> \n"};
const char *const Tab{"One\tTwo\n"};
const char *const Bell{"Hello!\a And welcome!"};
const char *const Path{"C:\\Program Files\\Vendor\\Application.exe"};
const char *const RegEx{"\\w\\([a-z]\\)"};
becomes
.. code-block:: c++
const char *const Quotes{R"(embedded "quotes")"};
const char *const Paragraph{"Line one.\nLine two.\nLine three.\n"};
const char *const SingleLine{"Single line.\n"};
const char *const TrailingSpace{"Look here -> \n"};
const char *const Tab{"One\tTwo\n"};
const char *const Bell{"Hello!\a And welcome!"};
const char *const Path{R"(C:\Program Files\Vendor\Application.exe)"};
const char *const RegEx{R"(\w\([a-z]\))"};
The presence of any of the following escapes can cause the string to be
converted to a raw string literal: ``\\``, ``\'``, ``\"``, ``\?``,
and octal or hexadecimal escapes for printable ASCII characters.
A string literal containing only escaped newlines is a common way of
writing lines of text output. Introducing physical newlines with raw
string literals in this case is likely to impede readability. These
string literals are left unchanged.
An escaped horizontal tab, form feed, or vertical tab prevents the string
literal from being converted. The presence of a horizontal tab, form feed or
vertical tab in source code is not visually obvious.
.. title:: clang-tidy - modernize-redundant-void-arg
modernize-redundant-void-arg
============================
Find and remove redundant ``void`` argument lists.
Examples:
=================================== ===========================
Initial code Code with applied fixes
=================================== ===========================
``int f(void);`` ``int f();``
``int (*f(void))(void);`` ``int (*f())();``
``typedef int (*f_t(void))(void);`` ``typedef int (*f_t())();``
``void (C::*p)(void);`` ``void (C::*p)();``
``C::C(void) {}`` ``C::C() {}``
``C::~C(void) {}`` ``C::~C() {}``
=================================== ===========================
.. title:: clang-tidy - modernize-replace-auto-ptr
modernize-replace-auto-ptr
==========================
This check replaces the uses of the deprecated class ``std::auto_ptr`` by
``std::unique_ptr`` (introduced in C++11). The transfer of ownership, done
by the copy-constructor and the assignment operator, is changed to match
``std::unique_ptr`` usage by using explicit calls to ``std::move()``.
Migration example:
.. code-block:: c++
-void take_ownership_fn(std::auto_ptr<int> int_ptr);
+void take_ownership_fn(std::unique_ptr<int> int_ptr);
void f(int x) {
- std::auto_ptr<int> a(new int(x));
- std::auto_ptr<int> b;
+ std::unique_ptr<int> a(new int(x));
+ std::unique_ptr<int> b;
- b = a;
- take_ownership_fn(b);
+ b = std::move(a);
+ take_ownership_fn(std::move(b));
}
Since ``std::move()`` is a library function declared in ``<utility>`` it may be
necessary to add this include. The check will add the include directive when
necessary.
Known Limitations
-----------------
* If headers modification is not activated or if a header is not allowed to be
changed this check will produce broken code (compilation error), where the
headers' code will stay unchanged while the code using them will be changed.
* Client code that declares a reference to an ``std::auto_ptr`` coming from
code that can't be migrated (such as a header coming from a 3\ :sup:`rd`
party library) will produce a compilation error after migration. This is
because the type of the reference will be changed to ``std::unique_ptr`` but
the type returned by the library won't change, binding a reference to
``std::unique_ptr`` from an ``std::auto_ptr``. This pattern doesn't make much
sense and usually ``std::auto_ptr`` are stored by value (otherwise what is
the point in using them instead of a reference or a pointer?).
.. code-block:: c++
// <3rd-party header...>
std::auto_ptr<int> get_value();
const std::auto_ptr<int> & get_ref();
// <calling code (with migration)...>
-std::auto_ptr<int> a(get_value());
+std::unique_ptr<int> a(get_value()); // ok, unique_ptr constructed from auto_ptr
-const std::auto_ptr<int> & p = get_ptr();
+const std::unique_ptr<int> & p = get_ptr(); // won't compile
* Non-instantiated templates aren't modified.
.. code-block:: c++
template <typename X>
void f() {
std::auto_ptr<X> p;
}
// only 'f<int>()' (or similar) will trigger the replacement.
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. title:: clang-tidy - modernize-replace-disallow-copy-and-assign-macro
modernize-replace-disallow-copy-and-assign-macro
================================================
Finds macro expansions of ``DISALLOW_COPY_AND_ASSIGN(Type)`` and replaces them
with a deleted copy constructor and a deleted assignment operator.
Before the ``delete`` keyword was introduced in C++11 it was common practice to
declare a copy constructor and an assignment operator as a private members. This
effectively makes them unusable to the public API of a class.
With the advent of the ``delete`` keyword in C++11 we can abandon the
``private`` access of the copy constructor and the assignment operator and
delete the methods entirely.
When running this check on a code like this:
.. code-block:: c++
class Foo {
private:
DISALLOW_COPY_AND_ASSIGN(Foo);
};
It will be transformed to this:
.. code-block:: c++
class Foo {
private:
Foo(const Foo &) = delete;
const Foo &operator=(const Foo &) = delete;
};
Known Limitations
-----------------
* Notice that the migration example above leaves the ``private`` access
specification untouched. You might want to run the check :doc:`modernize-use-equals-delete
<modernize-use-equals-delete>` to get warnings for deleted functions in
private sections.
Options
-------
.. option:: MacroName
A string specifying the macro name whose expansion will be replaced.
Default is `DISALLOW_COPY_AND_ASSIGN`.
See: https://en.cppreference.com/w/cpp/language/function#Deleted_functions
.. title:: clang-tidy - modernize-replace-random-shuffle
modernize-replace-random-shuffle
================================
This check will find occurrences of ``std::random_shuffle`` and replace it with ``std::shuffle``. In C++17 ``std::random_shuffle`` will no longer be available and thus we need to replace it.
Below are two examples of what kind of occurrences will be found and two examples of what it will be replaced with.
.. code-block:: c++
std::vector<int> v;
// First example
std::random_shuffle(vec.begin(), vec.end());
// Second example
std::random_shuffle(vec.begin(), vec.end(), randomFunc);
Both of these examples will be replaced with:
.. code-block:: c++
std::shuffle(vec.begin(), vec.end(), std::mt19937(std::random_device()()));
The second example will also receive a warning that ``randomFunc`` is no longer supported in the same way as before so if the user wants the same functionality, the user will need to change the implementation of the ``randomFunc``.
One thing to be aware of here is that ``std::random_device`` is quite expensive to initialize. So if you are using the code in a performance critical place, you probably want to initialize it elsewhere.
Another thing is that the seeding quality of the suggested fix is quite poor: ``std::mt19937`` has an internal state of 624 32-bit integers, but is only seeded with a single integer. So if you require
higher quality randomness, you should consider seeding better, for example:
.. code-block:: c++
std::shuffle(v.begin(), v.end(), []() {
std::mt19937::result_type seeds[std::mt19937::state_size];
std::random_device device;
std::uniform_int_distribution<typename std::mt19937::result_type> dist;
std::generate(std::begin(seeds), std::end(seeds), [&] { return dist(device); });
std::seed_seq seq(std::begin(seeds), std::end(seeds));
return std::mt19937(seq);
}());
.. title:: clang-tidy - modernize-return-braced-init-list
modernize-return-braced-init-list
=================================
Replaces explicit calls to the constructor in a return with a braced
initializer list. This way the return type is not needlessly duplicated in the
function definition and the return statement.
.. code:: c++
Foo bar() {
Baz baz;
return Foo(baz);
}
// transforms to:
Foo bar() {
Baz baz;
return {baz};
}
.. title:: clang-tidy - modernize-shrink-to-fit
modernize-shrink-to-fit
=======================
Replace copy and swap tricks on shrinkable containers with the
``shrink_to_fit()`` method call.
The ``shrink_to_fit()`` method is more readable and more effective than
the copy and swap trick to reduce the capacity of a shrinkable container.
Note that, the ``shrink_to_fit()`` method is only available in C++11 and up.
.. title:: clang-tidy - modernize-unary-static-assert
modernize-unary-static-assert
=============================
The check diagnoses any ``static_assert`` declaration with an empty string literal
and provides a fix-it to replace the declaration with a single-argument ``static_assert`` declaration.
The check is only applicable for C++17 and later code.
The following code:
.. code-block:: c++
void f_textless(int a) {
static_assert(sizeof(a) <= 10, "");
}
is replaced by:
.. code-block:: c++
void f_textless(int a) {
static_assert(sizeof(a) <= 10);
}
.. title:: clang-tidy - modernize-use-auto
modernize-use-auto
==================
This check is responsible for using the ``auto`` type specifier for variable
declarations to *improve code readability and maintainability*. For example:
.. code-block:: c++
std::vector<int>::iterator I = my_container.begin();
// transforms to:
auto I = my_container.begin();
The ``auto`` type specifier will only be introduced in situations where the
variable type matches the type of the initializer expression. In other words
``auto`` should deduce the same type that was originally spelled in the source.
However, not every situation should be transformed:
.. code-block:: c++
int val = 42;
InfoStruct &I = SomeObject.getInfo();
// Should not become:
auto val = 42;
auto &I = SomeObject.getInfo();
In this example using ``auto`` for builtins doesn't improve readability. In
other situations it makes the code less self-documenting impairing readability
and maintainability. As a result, ``auto`` is used only introduced in specific
situations described below.
Iterators
---------
Iterator type specifiers tend to be long and used frequently, especially in
loop constructs. Since the functions generating iterators have a common format,
the type specifier can be replaced without obscuring the meaning of code while
improving readability and maintainability.
.. code-block:: c++
for (std::vector<int>::iterator I = my_container.begin(),
E = my_container.end();
I != E; ++I) {
}
// becomes
for (auto I = my_container.begin(), E = my_container.end(); I != E; ++I) {
}
The check will only replace iterator type-specifiers when all of the following
conditions are satisfied:
* The iterator is for one of the standard container in ``std`` namespace:
* ``array``
* ``deque``
* ``forward_list``
* ``list``
* ``vector``
* ``map``
* ``multimap``
* ``set``
* ``multiset``
* ``unordered_map``
* ``unordered_multimap``
* ``unordered_set``
* ``unordered_multiset``
* ``queue``
* ``priority_queue``
* ``stack``
* The iterator is one of the possible iterator types for standard containers:
* ``iterator``
* ``reverse_iterator``
* ``const_iterator``
* ``const_reverse_iterator``
* In addition to using iterator types directly, typedefs or other ways of
referring to those types are also allowed. However, implementation-specific
types for which a type like ``std::vector<int>::iterator`` is itself a
typedef will not be transformed. Consider the following examples:
.. code-block:: c++
// The following direct uses of iterator types will be transformed.
std::vector<int>::iterator I = MyVec.begin();
{
using namespace std;
list<int>::iterator I = MyList.begin();
}
// The type specifier for J would transform to auto since it's a typedef
// to a standard iterator type.
typedef std::map<int, std::string>::const_iterator map_iterator;
map_iterator J = MyMap.begin();
// The following implementation-specific iterator type for which
// std::vector<int>::iterator could be a typedef would not be transformed.
__gnu_cxx::__normal_iterator<int*, std::vector> K = MyVec.begin();
* The initializer for the variable being declared is not a braced initializer
list. Otherwise, use of ``auto`` would cause the type of the variable to be
deduced as ``std::initializer_list``.
New expressions
---------------
Frequently, when a pointer is declared and initialized with ``new``, the
pointee type is written twice: in the declaration type and in the
``new`` expression. In this cases, the declaration type can be replaced with
``auto`` improving readability and maintainability.
.. code-block:: c++
TypeName *my_pointer = new TypeName(my_param);
// becomes
auto *my_pointer = new TypeName(my_param);
The check will also replace the declaration type in multiple declarations, if
the following conditions are satisfied:
* All declared variables have the same type (i.e. all of them are pointers to
the same type).
* All declared variables are initialized with a ``new`` expression.
* The types of all the new expressions are the same than the pointee of the
declaration type.
.. code-block:: c++
TypeName *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
// becomes
auto *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
Cast expressions
----------------
Frequently, when a variable is declared and initialized with a cast, the
variable type is written twice: in the declaration type and in the
cast expression. In this cases, the declaration type can be replaced with
``auto`` improving readability and maintainability.
.. code-block:: c++
TypeName *my_pointer = static_cast<TypeName>(my_param);
// becomes
auto *my_pointer = static_cast<TypeName>(my_param);
The check handles ``static_cast``, ``dynamic_cast``, ``const_cast``,
``reinterpret_cast``, functional casts, C-style casts and function templates
that behave as casts, such as ``llvm::dyn_cast``, ``boost::lexical_cast`` and
``gsl::narrow_cast``. Calls to function templates are considered to behave as
casts if the first template argument is explicit and is a type, and the function
returns that type, or a pointer or reference to it.
Known Limitations
-----------------
* If the initializer is an explicit conversion constructor, the check will not
replace the type specifier even though it would be safe to do so.
* User-defined iterators are not handled at this time.
Options
-------
.. option:: MinTypeNameLength
If the option is set to non-zero (default `5`), the check will ignore type
names having a length less than the option value. The option affects
expressions only, not iterators.
Spaces between multi-lexeme type names (``long int``) are considered as one.
If the :option:`RemoveStars` option (see below) is set to `true`, then ``*s``
in the type are also counted as a part of the type name.
.. code-block:: c++
// MinTypeNameLength = 0, RemoveStars=0
int a = static_cast<int>(foo()); // ---> auto a = ...
// length(bool *) = 4
bool *b = new bool; // ---> auto *b = ...
unsigned c = static_cast<unsigned>(foo()); // ---> auto c = ...
// MinTypeNameLength = 5, RemoveStars=0
int a = static_cast<int>(foo()); // ---> int a = ...
bool b = static_cast<bool>(foo()); // ---> bool b = ...
bool *pb = static_cast<bool*>(foo()); // ---> bool *pb = ...
unsigned c = static_cast<unsigned>(foo()); // ---> auto c = ...
// length(long <on-or-more-spaces> int) = 8
long int d = static_cast<long int>(foo()); // ---> auto d = ...
// MinTypeNameLength = 5, RemoveStars=1
int a = static_cast<int>(foo()); // ---> int a = ...
// length(int * * ) = 5
int **pa = static_cast<int**>(foo()); // ---> auto pa = ...
bool b = static_cast<bool>(foo()); // ---> bool b = ...
bool *pb = static_cast<bool*>(foo()); // ---> auto pb = ...
unsigned c = static_cast<unsigned>(foo()); // ---> auto c = ...
long int d = static_cast<long int>(foo()); // ---> auto d = ...
.. option:: RemoveStars
If the option is set to `true` (default is `false`), the check will remove
stars from the non-typedef pointer types when replacing type names with
``auto``. Otherwise, the check will leave stars. For example:
.. code-block:: c++
TypeName *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
// RemoveStars = 0
auto *my_first_pointer = new TypeName, *my_second_pointer = new TypeName;
// RemoveStars = 1
auto my_first_pointer = new TypeName, my_second_pointer = new TypeName;
.. title:: clang-tidy - modernize-use-bool-literals
modernize-use-bool-literals
===========================
Finds integer literals which are cast to ``bool``.
.. code-block:: c++
bool p = 1;
bool f = static_cast<bool>(1);
std::ios_base::sync_with_stdio(0);
bool x = p ? 1 : 0;
// transforms to
bool p = true;
bool f = true;
std::ios_base::sync_with_stdio(false);
bool x = p ? true : false;
Options
-------
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. title:: clang-tidy - modernize-use-default-member-init
modernize-use-default-member-init
=================================
This check converts a default constructor's member initializers into the new
default member initializers in C++11. Other member initializers that match the
default member initializer are removed. This can reduce repeated code or allow
use of '= default'.
.. code-block:: c++
struct A {
A() : i(5), j(10.0) {}
A(int i) : i(i), j(10.0) {}
int i;
double j;
};
// becomes
struct A {
A() {}
A(int i) : i(i) {}
int i{5};
double j{10.0};
};
.. note::
Only converts member initializers for built-in types, enums, and pointers.
The `readability-redundant-member-init` check will remove redundant member
initializers for classes.
Options
-------
.. option:: UseAssignment
If this option is set to `true` (default is `false`), the check will initialise
members with an assignment. For example:
.. code-block:: c++
struct A {
A() {}
A(int i) : i(i) {}
int i = 5;
double j = 10.0;
};
.. option:: IgnoreMacros
If this option is set to `true` (default is `true`), the check will not warn
about members declared inside macros.
:orphan:
.. title:: clang-tidy - modernize-use-default
.. meta::
:http-equiv=refresh: 5;URL=modernize-use-equals-default.html
modernize-use-default
=====================
This check has been renamed to
`modernize-use-equals-default <modernize-use-equals-default.html>`_.
.. title:: clang-tidy - modernize-use-emplace
modernize-use-emplace
=====================
The check flags insertions to an STL-style container done by calling the
``push_back`` method with an explicitly-constructed temporary of the container
element type. In this case, the corresponding ``emplace_back`` method
results in less verbose and potentially more efficient code.
Right now the check doesn't support ``push_front`` and ``insert``.
It also doesn't support ``insert`` functions for associative containers
because replacing ``insert`` with ``emplace`` may result in
`speed regression <https://htmlpreview.github.io/?https://github.com/HowardHinnant/papers/blob/master/insert_vs_emplace.html>`_, but it might get support with some addition flag in the future.
By default only ``std::vector``, ``std::deque``, ``std::list`` are considered.
This list can be modified using the :option:`ContainersWithPushBack` option.
Before:
.. code-block:: c++
std::vector<MyClass> v;
v.push_back(MyClass(21, 37));
std::vector<std::pair<int, int>> w;
w.push_back(std::pair<int, int>(21, 37));
w.push_back(std::make_pair(21L, 37L));
After:
.. code-block:: c++
std::vector<MyClass> v;
v.emplace_back(21, 37);
std::vector<std::pair<int, int>> w;
w.emplace_back(21, 37);
w.emplace_back(21L, 37L);
By default, the check is able to remove unnecessary ``std::make_pair`` and
``std::make_tuple`` calls from ``push_back`` calls on containers of
``std::pair`` and ``std::tuple``. Custom tuple-like types can be modified by
the :option:`TupleTypes` option; custom make functions can be modified by the
:option:`TupleMakeFunctions` option.
The other situation is when we pass arguments that will be converted to a type
inside a container.
Before:
.. code-block:: c++
std::vector<boost::optional<std::string> > v;
v.push_back("abc");
After:
.. code-block:: c++
std::vector<boost::optional<std::string> > v;
v.emplace_back("abc");
In some cases the transformation would be valid, but the code wouldn't be
exception safe. In this case the calls of ``push_back`` won't be replaced.
.. code-block:: c++
std::vector<std::unique_ptr<int>> v;
v.push_back(std::unique_ptr<int>(new int(0)));
auto *ptr = new int(1);
v.push_back(std::unique_ptr<int>(ptr));
This is because replacing it with ``emplace_back`` could cause a leak of this
pointer if ``emplace_back`` would throw exception before emplacement (e.g. not
enough memory to add a new element).
For more info read item 42 - "Consider emplacement instead of insertion." of
Scott Meyers "Effective Modern C++".
The default smart pointers that are considered are ``std::unique_ptr``,
``std::shared_ptr``, ``std::auto_ptr``. To specify other smart pointers or
other classes use the :option:`SmartPointers` option.
Check also doesn't fire if any argument of the constructor call would be:
- a bit-field (bit-fields can't bind to rvalue/universal reference)
- a ``new`` expression (to avoid leak)
- if the argument would be converted via derived-to-base cast.
This check requires C++11 or higher to run.
Options
-------
.. option:: ContainersWithPushBack
Semicolon-separated list of class names of custom containers that support
``push_back``.
.. option:: IgnoreImplicitConstructors
When `true`, the check will ignore implicitly constructed arguments of
``push_back``, e.g.
.. code-block:: c++
std::vector<std::string> v;
v.push_back("a"); // Ignored when IgnoreImplicitConstructors is `true`.
Default is `false`.
.. option:: SmartPointers
Semicolon-separated list of class names of custom smart pointers.
.. option:: TupleTypes
Semicolon-separated list of ``std::tuple``-like class names.
.. option:: TupleMakeFunctions
Semicolon-separated list of ``std::make_tuple``-like function names. Those
function calls will be removed from ``push_back`` calls and turned into
``emplace_back``.
Example
^^^^^^^
.. code-block:: c++
std::vector<MyTuple<int, bool, char>> x;
x.push_back(MakeMyTuple(1, false, 'x'));
transforms to:
.. code-block:: c++
std::vector<MyTuple<int, bool, char>> x;
x.emplace_back(1, false, 'x');
when :option:`TupleTypes` is set to ``MyTuple`` and :option:`TupleMakeFunctions`
is set to ``MakeMyTuple``.
.. title:: clang-tidy - modernize-use-equals-default
modernize-use-equals-default
============================
This check replaces default bodies of special member functions with ``=
default;``. The explicitly defaulted function declarations enable more
opportunities in optimization, because the compiler might treat explicitly
defaulted functions as trivial.
.. code-block:: c++
struct A {
A() {}
~A();
};
A::~A() {}
// becomes
struct A {
A() = default;
~A();
};
A::~A() = default;
.. note::
Move-constructor and move-assignment operator are not supported yet.
Options
-------
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. title:: clang-tidy - modernize-use-equals-delete
modernize-use-equals-delete
===========================
This check marks unimplemented private special member functions with ``= delete``.
To avoid false-positives, this check only applies in a translation unit that has
all other member functions implemented.
.. code-block:: c++
struct A {
private:
A(const A&);
A& operator=(const A&);
};
// becomes
struct A {
private:
A(const A&) = delete;
A& operator=(const A&) = delete;
};
.. option:: IgnoreMacros
If this option is set to `true` (default is `true`), the check will not warn
about functions declared inside macros.
.. title:: clang-tidy - modernize-use-nodiscard
modernize-use-nodiscard
=======================
Adds ``[[nodiscard]]`` attributes (introduced in C++17) to member functions in
order to highlight at compile time which return values should not be ignored.
Member functions need to satisfy the following conditions to be considered by
this check:
- no ``[[nodiscard]]``, ``[[noreturn]]``,
``__attribute__((warn_unused_result))``,
``[[clang::warn_unused_result]]`` nor ``[[gcc::warn_unused_result]]``
attribute,
- non-void return type,
- non-template return types,
- const member function,
- non-variadic functions,
- no non-const reference parameters,
- no pointer parameters,
- no template parameters,
- no template function parameters,
- not be a member of a class with mutable member variables,
- no Lambdas,
- no conversion functions.
Such functions have no means of altering any state or passing values other than
via the return type. Unless the member functions are altering state via some
external call (e.g. I/O).
Example
-------
.. code-block:: c++
bool empty() const;
bool empty(int i) const;
transforms to:
.. code-block:: c++
[[nodiscard]] bool empty() const;
[[nodiscard]] bool empty(int i) const;
Options
-------
.. option:: ReplacementString
Specifies a macro to use instead of ``[[nodiscard]]``. This is useful when
maintaining source code that needs to compile with a pre-C++17 compiler.
Example
^^^^^^^
.. code-block:: c++
bool empty() const;
bool empty(int i) const;
transforms to:
.. code-block:: c++
NO_DISCARD bool empty() const;
NO_DISCARD bool empty(int i) const;
if the :option:`ReplacementString` option is set to `NO_DISCARD`.
.. note::
If the :option:`ReplacementString` is not a C++ attribute, but instead a
macro, then that macro must be defined in scope or the fix-it will not be
applied.
.. note::
For alternative ``__attribute__`` syntax options to mark functions as
``[[nodiscard]]`` in non-c++17 source code.
See https://clang.llvm.org/docs/AttributeReference.html#nodiscard-warn-unused-result
.. title:: clang-tidy - modernize-use-noexcept
modernize-use-noexcept
======================
This check replaces deprecated dynamic exception specifications with
the appropriate noexcept specification (introduced in C++11). By
default this check will replace ``throw()`` with ``noexcept``,
and ``throw(<exception>[,...])`` or ``throw(...)`` with
``noexcept(false)``.
Example
-------
.. code-block:: c++
void foo() throw();
void bar() throw(int) {}
transforms to:
.. code-block:: c++
void foo() noexcept;
void bar() noexcept(false) {}
Options
-------
.. option:: ReplacementString
Users can use :option:`ReplacementString` to specify a macro to use
instead of ``noexcept``. This is useful when maintaining source code
that uses custom exception specification marking other than
``noexcept``. Fix-it hints will only be generated for non-throwing
specifications.
Example
^^^^^^^
.. code-block:: c++
void bar() throw(int);
void foo() throw();
transforms to:
.. code-block:: c++
void bar() throw(int); // No fix-it generated.
void foo() NOEXCEPT;
if the :option:`ReplacementString` option is set to `NOEXCEPT`.
.. option:: UseNoexceptFalse
Enabled by default, disabling will generate fix-it hints that remove
throwing dynamic exception specs, e.g., ``throw(<something>)``,
completely without providing a replacement text, except for
destructors and delete operators that are ``noexcept(true)`` by
default.
Example
^^^^^^^
.. code-block:: c++
void foo() throw(int) {}
struct bar {
void foobar() throw(int);
void operator delete(void *ptr) throw(int);
void operator delete[](void *ptr) throw(int);
~bar() throw(int);
}
transforms to:
.. code-block:: c++
void foo() {}
struct bar {
void foobar();
void operator delete(void *ptr) noexcept(false);
void operator delete[](void *ptr) noexcept(false);
~bar() noexcept(false);
}
if the :option:`UseNoexceptFalse` option is set to `false`.
.. title:: clang-tidy - modernize-use-nullptr
modernize-use-nullptr
=====================
The check converts the usage of null pointer constants (eg. ``NULL``, ``0``)
to use the new C++11 ``nullptr`` keyword.
Example
-------
.. code-block:: c++
void assignment() {
char *a = NULL;
char *b = 0;
char c = 0;
}
int *ret_ptr() {
return 0;
}
transforms to:
.. code-block:: c++
void assignment() {
char *a = nullptr;
char *b = nullptr;
char c = 0;
}
int *ret_ptr() {
return nullptr;
}
Options
-------
.. option:: NullMacros
Comma-separated list of macro names that will be transformed along with
``NULL``. By default this check will only replace the ``NULL`` macro and will
skip any similar user-defined macros.
Example
^^^^^^^
.. code-block:: c++
#define MY_NULL (void*)0
void assignment() {
void *p = MY_NULL;
}
transforms to:
.. code-block:: c++
#define MY_NULL NULL
void assignment() {
int *p = nullptr;
}
if the :option:`NullMacros` option is set to ``MY_NULL``.
.. title:: clang-tidy - modernize-use-override
modernize-use-override
======================
Adds ``override`` (introduced in C++11) to overridden virtual functions and
removes ``virtual`` from those functions as it is not required.
``virtual`` on non base class implementations was used to help indicate to the
user that a function was virtual. C++ compilers did not use the presence of
this to signify an overridden function.
In C++ 11 ``override`` and ``final`` keywords were introduced to allow
overridden functions to be marked appropriately. Their presence allows
compilers to verify that an overridden function correctly overrides a base
class implementation.
This can be useful as compilers can generate a compile time error when:
- The base class implementation function signature changes.
- The user has not created the override with the correct signature.
Options
-------
.. option:: IgnoreDestructors
If set to `true`, this check will not diagnose destructors. Default is `false`.
.. option:: AllowOverrideAndFinal
If set to `true`, this check will not diagnose ``override`` as redundant
with ``final``. This is useful when code will be compiled by a compiler with
warning/error checking flags requiring ``override`` explicitly on overridden
members, such as ``gcc -Wsuggest-override``/``gcc -Werror=suggest-override``.
Default is `false`.
.. option:: OverrideSpelling
Specifies a macro to use instead of ``override``. This is useful when
maintaining source code that also needs to compile with a pre-C++11
compiler.
.. option:: FinalSpelling
Specifies a macro to use instead of ``final``. This is useful when
maintaining source code that also needs to compile with a pre-C++11
compiler.
.. note::
For more information on the use of ``override`` see https://en.cppreference.com/w/cpp/language/override
.. title:: clang-tidy - modernize-use-trailing-return-type
modernize-use-trailing-return-type
==================================
Rewrites function signatures to use a trailing return type
(introduced in C++11). This transformation is purely stylistic.
The return type before the function name is replaced by ``auto``
and inserted after the function parameter list (and qualifiers).
Example
-------
.. code-block:: c++
int f1();
inline int f2(int arg) noexcept;
virtual float f3() const && = delete;
transforms to:
.. code-block:: c++
auto f1() -> int;
inline auto f2(int arg) -> int noexcept;
virtual auto f3() const && -> float = delete;
Known Limitations
-----------------
The following categories of return types cannot be rewritten currently:
* function pointers
* member function pointers
* member pointers
Unqualified names in the return type might erroneously refer to different entities after the rewrite.
Preventing such errors requires a full lookup of all unqualified names present in the return type in the scope of the trailing return type location.
This location includes e.g. function parameter names and members of the enclosing class (including all inherited classes).
Such a lookup is currently not implemented.
Given the following piece of code
.. code-block:: c++
struct S { long long value; };
S f(unsigned S) { return {S * 2}; }
class CC {
int S;
struct S m();
};
S CC::m() { return {0}; }
a careless rewrite would produce the following output:
.. code-block:: c++
struct S { long long value; };
auto f(unsigned S) -> S { return {S * 2}; } // error
class CC {
int S;
auto m() -> struct S;
};
auto CC::m() -> S { return {0}; } // error
This code fails to compile because the S in the context of f refers to the equally named function parameter.
Similarly, the S in the context of m refers to the equally named class member.
The check can currently only detect and avoid a clash with a function parameter name.
.. title:: clang-tidy - modernize-use-transparent-functors
modernize-use-transparent-functors
==================================
Prefer transparent functors to non-transparent ones. When using transparent
functors, the type does not need to be repeated. The code is easier to read,
maintain and less prone to errors. It is not possible to introduce unwanted
conversions.
.. code-block:: c++
// Non-transparent functor
std::map<int, std::string, std::greater<int>> s;
// Transparent functor.
std::map<int, std::string, std::greater<>> s;
// Non-transparent functor
using MyFunctor = std::less<MyType>;
It is not always a safe transformation though. The following case will be
untouched to preserve the semantics.
.. code-block:: c++
// Non-transparent functor
std::map<const char *, std::string, std::greater<std::string>> s;
Options
-------
.. option:: SafeMode
If the option is set to `true`, the check will not diagnose cases where
using a transparent functor cannot be guaranteed to produce identical results
as the original code. The default value for this option is `false`.
This check requires using C++14 or higher to run.
.. title:: clang-tidy - modernize-use-uncaught-exceptions
modernize-use-uncaught-exceptions
====================================
This check will warn on calls to ``std::uncaught_exception`` and replace them
with calls to ``std::uncaught_exceptions``, since ``std::uncaught_exception``
was deprecated in C++17.
Below are a few examples of what kind of occurrences will be found and what
they will be replaced with.
.. code-block:: c++
#define MACRO1 std::uncaught_exception
#define MACRO2 std::uncaught_exception
int uncaught_exception() {
return 0;
}
int main() {
int res;
res = uncaught_exception();
// No warning, since it is not the deprecated function from namespace std
res = MACRO2();
// Warning, but will not be replaced
res = std::uncaught_exception();
// Warning and replaced
using std::uncaught_exception;
// Warning and replaced
res = uncaught_exception();
// Warning and replaced
}
After applying the fixes the code will look like the following:
.. code-block:: c++
#define MACRO1 std::uncaught_exception
#define MACRO2 std::uncaught_exception
int uncaught_exception() {
return 0;
}
int main() {
int res;
res = uncaught_exception();
res = MACRO2();
res = std::uncaught_exceptions();
using std::uncaught_exceptions;
res = uncaught_exceptions();
}
.. title:: clang-tidy - modernize-use-using
modernize-use-using
===================
The check converts the usage of ``typedef`` with ``using`` keyword.
Before:
.. code-block:: c++
typedef int variable;
class Class{};
typedef void (Class::* MyPtrType)() const;
typedef struct { int a; } R_t, *R_p;
After:
.. code-block:: c++
using variable = int;
class Class{};
using MyPtrType = void (Class::*)() const;
using R_t = struct { int a; };
using R_p = R_t*;
This check requires using C++11 or higher to run.
Options
-------
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. title:: clang-tidy - mpi-buffer-deref
mpi-buffer-deref
================
This check verifies if a buffer passed to an MPI (Message Passing Interface)
function is sufficiently dereferenced. Buffers should be passed as a single
pointer or array. As MPI function signatures specify ``void *`` for their buffer
types, insufficiently dereferenced buffers can be passed, like for example as
double pointers or multidimensional arrays, without a compiler warning emitted.
Examples:
.. code-block:: c++
// A double pointer is passed to the MPI function.
char *buf;
MPI_Send(&buf, 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
// A multidimensional array is passed to the MPI function.
short buf[1][1];
MPI_Send(buf, 1, MPI_SHORT, 0, 0, MPI_COMM_WORLD);
// A pointer to an array is passed to the MPI function.
short *buf[1];
MPI_Send(buf, 1, MPI_SHORT, 0, 0, MPI_COMM_WORLD);
.. title:: clang-tidy - mpi-type-mismatch
mpi-type-mismatch
=================
This check verifies if buffer type and MPI (Message Passing Interface) datatype
pairs match for used MPI functions. All MPI datatypes defined by the MPI
standard (3.1) are verified by this check. User defined typedefs, custom MPI
datatypes and null pointer constants are skipped, in the course of verification.
Example:
.. code-block:: c++
// In this case, the buffer type matches MPI datatype.
char buf;
MPI_Send(&buf, 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
// In the following case, the buffer type does not match MPI datatype.
int buf;
MPI_Send(&buf, 1, MPI_CHAR, 0, 0, MPI_COMM_WORLD);
.. title:: clang-tidy - objc-avoid-nserror-init
objc-avoid-nserror-init
=======================
Finds improper initialization of ``NSError`` objects.
According to Apple developer document, we should always use factory method
``errorWithDomain:code:userInfo:`` to create new NSError objects instead
of ``[NSError alloc] init]``. Otherwise it will lead to a warning message
during runtime.
The corresponding information about ``NSError`` creation: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html
.. title:: clang-tidy - objc-dealloc-in-category
objc-dealloc-in-category
========================
Finds implementations of ``-dealloc`` in Objective-C categories. The category
implementation will override any ``-dealloc`` in the class implementation,
potentially causing issues.
Classes implement ``-dealloc`` to perform important actions to deallocate
an object. If a category on the class implements ``-dealloc``, it will
override the class's implementation and unexpected deallocation behavior
may occur.
.. title:: clang-tidy - objc-forbidden-subclassing
objc-forbidden-subclassing
==========================
Finds Objective-C classes which are subclasses of classes which are not designed
to be subclassed.
By default, includes a list of Objective-C classes which are publicly documented
as not supporting subclassing.
.. note::
Instead of using this check, for code under your control, you should add
``__attribute__((objc_subclassing_restricted))`` before your ``@interface``
declarations to ensure the compiler prevents others from subclassing your
Objective-C classes.
See https://clang.llvm.org/docs/AttributeReference.html#objc-subclassing-restricted
Options
-------
.. option:: ForbiddenSuperClassNames
Semicolon-separated list of names of Objective-C classes which
do not support subclassing.
Defaults to `ABNewPersonViewController;ABPeoplePickerNavigationController;ABPersonViewController;ABUnknownPersonViewController;NSHashTable;NSMapTable;NSPointerArray;NSPointerFunctions;NSTimer;UIActionSheet;UIAlertView;UIImagePickerController;UITextInputMode;UIWebView`.
.. title:: clang-tidy - objc-missing-hash
objc-missing-hash
=================
Finds Objective-C implementations that implement ``-isEqual:`` without also
appropriately implementing ``-hash``.
Apple documentation highlights that objects that are equal must have the same
hash value:
https://developer.apple.com/documentation/objectivec/1418956-nsobject/1418795-isequal?language=objc
Note that the check only verifies the presence of ``-hash`` in scenarios where
its omission could result in unexpected behavior. The verification of the
implementation of ``-hash`` is the responsibility of the developer, e.g.,
through the addition of unit tests to verify the implementation.
.. title:: clang-tidy - objc-nsinvocation-argument-lifetime
objc-nsinvocation-argument-lifetime
===================================
Finds calls to ``NSInvocation`` methods under ARC that don't have proper
argument object lifetimes. When passing Objective-C objects as parameters
to the ``NSInvocation`` methods ``getArgument:atIndex:`` and
``getReturnValue:``, the values are copied by value into the argument pointer,
which leads to to incorrect releasing behavior if the object pointers are
not declared ``__unsafe_unretained``.
For code:
.. code-block:: objc
id arg;
[invocation getArgument:&arg atIndex:2];
__strong id returnValue;
[invocation getReturnValue:&returnValue];
The fix will be:
.. code-block:: objc
__unsafe_unretained id arg;
[invocation getArgument:&arg atIndex:2];
__unsafe_unretained id returnValue;
[invocation getReturnValue:&returnValue];
The check will warn on being passed instance variable references that have
lifetimes other than ``__unsafe_unretained``, but does not propose a fix:
.. code-block:: objc
// "id _returnValue" is declaration of instance variable of class.
[invocation getReturnValue:&self->_returnValue];
.. title:: clang-tidy - objc-property-declaration
objc-property-declaration
=========================
Finds property declarations in Objective-C files that do not follow the pattern
of property names in Apple's programming guide. The property name should be
in the format of Lower Camel Case.
For code:
.. code-block:: objc
@property(nonatomic, assign) int LowerCamelCase;
The fix will be:
.. code-block:: objc
@property(nonatomic, assign) int lowerCamelCase;
The check will only fix 'CamelCase' to 'camelCase'. In some other cases we will
only provide warning messages since the property name could be complicated.
Users will need to come up with a proper name by their own.
This check also accepts special acronyms as prefixes or suffixes. Such prefixes or suffixes
will suppress the Lower Camel Case check according to the guide:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html#//apple_ref/doc/uid/20001281-1002931-BBCFHEAB
For a full list of well-known acronyms:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/APIAbbreviations.html#//apple_ref/doc/uid/20001285-BCIHCGAE
The corresponding style rule: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-1001757
The check will also accept property declared in category with a prefix of
lowercase letters followed by a '_' to avoid naming conflict. For example:
.. code-block:: objc
@property(nonatomic, assign) int abc_lowerCamelCase;
The corresponding style rule: https://developer.apple.com/library/content/qa/qa1908/_index.html
.. title:: clang-tidy - objc-super-self
objc-super-self
===============
Finds invocations of ``-self`` on super instances in initializers of subclasses
of ``NSObject`` and recommends calling a superclass initializer instead.
Invoking ``-self`` on super instances in initializers is a common programmer
error when the programmer's original intent is to call a superclass
initializer. Failing to call a superclass initializer breaks initializer
chaining and can result in invalid object initialization.
.. title:: clang-tidy - openmp-exception-escape
openmp-exception-escape
=======================
Analyzes OpenMP Structured Blocks and checks that no exception escapes
out of the Structured Block it was thrown in.
As per the OpenMP specification, a structured block is an executable statement,
possibly compound, with a single entry at the top and a single exit at the
bottom. Which means, ``throw`` may not be used to to 'exit' out of the
structured block. If an exception is not caught in the same structured block
it was thrown in, the behaviour is undefined.
FIXME: this check does not model SEH, ``setjmp``/``longjmp``.
WARNING! This check may be expensive on large source files.
Options
-------
.. option:: IgnoredExceptions
Comma-separated list containing type names which are not counted as thrown
exceptions in the check. Default value is an empty string.
.. title:: clang-tidy - openmp-use-default-none
openmp-use-default-none
=======================
Finds OpenMP directives that are allowed to contain a ``default`` clause,
but either don't specify it or the clause is specified but with the kind
other than ``none``, and suggests to use the ``default(none)`` clause.
Using ``default(none)`` clause forces developers to explicitly specify data
sharing attributes for the variables referenced in the construct,
thus making it obvious which variables are referenced, and what is their
data sharing attribute, thus increasing readability and possibly making errors
easier to spot.
Example
-------
.. code-block:: c++
// ``for`` directive can not have ``default`` clause, no diagnostics.
void n0(const int a) {
#pragma omp for
for (int b = 0; b < a; b++)
;
}
// ``parallel`` directive.
// ``parallel`` directive can have ``default`` clause, but said clause is not
// specified, diagnosed.
void p0_0() {
#pragma omp parallel
;
// WARNING: OpenMP directive ``parallel`` does not specify ``default``
// clause. Consider specifying ``default(none)`` clause.
}
// ``parallel`` directive can have ``default`` clause, and said clause is
// specified, with ``none`` kind, all good.
void p0_1() {
#pragma omp parallel default(none)
;
}
// ``parallel`` directive can have ``default`` clause, and said clause is
// specified, but with ``shared`` kind, which is not ``none``, diagnose.
void p0_2() {
#pragma omp parallel default(shared)
;
// WARNING: OpenMP directive ``parallel`` specifies ``default(shared)``
// clause. Consider using ``default(none)`` clause instead.
}
// ``parallel`` directive can have ``default`` clause, and said clause is
// specified, but with ``firstprivate`` kind, which is not ``none``, diagnose.
void p0_3() {
#pragma omp parallel default(firstprivate)
;
// WARNING: OpenMP directive ``parallel`` specifies ``default(firstprivate)``
// clause. Consider using ``default(none)`` clause instead.
}
.. title:: clang-tidy - abseil-duration-addition
abseil-duration-addition
========================
Check for cases where addition should be performe.. title:: clang-tidy - performance-faster-string-find
performance-faster-string-find
==============================
Optimize calls to ``std::string::find()`` and friends when the needle passed is
a single character string literal. The character literal overload is more
efficient.
Examples:
.. code-block:: c++
str.find("A");
// becomes
str.find('A');
Options
-------
.. option:: StringLikeClasses
Semicolon-separated list of names of string-like classes. By default only
``::std::basic_string`` and ``::std::basic_string_view`` are considered.
The check will only consider member functions named ``find``, ``rfind``,
``find_first_of``, ``find_first_not_of``, ``find_last_of``, or
``find_last_not_of`` within these classes.
.. title:: clang-tidy - performance-for-range-copy
performance-for-range-copy
==========================
Finds C++11 for ranges where the loop variable is copied in each iteration but
it would suffice to obtain it by const reference.
The check is only applied to loop variables of types that are expensive to copy
which means they are not trivially copyable or have a non-trivial copy
constructor or destructor.
To ensure that it is safe to replace the copy with a const reference the
following heuristic is employed:
1. The loop variable is const qualified.
2. The loop variable is not const, but only const methods or operators are
invoked on it, or it is used as const reference or value argument in
constructors or function calls.
Options
-------
.. option:: WarnOnAllAutoCopies
When `true`, warns on any use of `auto` as the type of the range-based for
loop variable. Default is `false`.
.. option:: AllowedTypes
A semicolon-separated list of names of types allowed to be copied in each
iteration. Regular expressions are accepted, e.g. `[Rr]ef(erence)?$` matches
every type with suffix `Ref`, `ref`, `Reference` and `reference`. The default
is empty. If a name in the list contains the sequence `::` it is matched
against the qualified typename (i.e. `namespace::Type`, otherwise it is
matched against only the type name (i.e. `Type`).
:orphan:
.. title:: clang-tidy - performance-implicit-cast-in-loop
.. meta::
:http-equiv=refresh: 5;URL=performance-implicit-conversion-in-loop.html
performance-implicit-cast-in-loop
=================================
This check has been renamed to `performance-implicit-conversion-in-loop
<performance-implicit-conversion-in-loop.html>`_.
.. title:: clang-tidy - performance-implicit-conversion-in-loop
performance-implicit-conversion-in-loop
=======================================
This warning appears in a range-based loop with a loop variable of const ref
type where the type of the variable does not match the one returned by the
iterator. This means that an implicit conversion happens, which can for example
result in expensive deep copies.
Example:
.. code-block:: c++
map<int, vector<string>> my_map;
for (const pair<int, vector<string>>& p : my_map) {}
// The iterator type is in fact pair<const int, vector<string>>, which means
// that the compiler added a conversion, resulting in a copy of the vectors.
The easiest solution is usually to use ``const auto&`` instead of writing the
type manually.
.. title:: clang-tidy - performance-inefficient-algorithm
performance-inefficient-algorithm
=================================
Warns on inefficient use of STL algorithms on associative containers.
Associative containers implements some of the algorithms as methods which
should be preferred to the algorithms in the algorithm header. The methods
can take advantage of the order of the elements.
.. code-block:: c++
std::set<int> s;
auto it = std::find(s.begin(), s.end(), 43);
// becomes
auto it = s.find(43);
.. code-block:: c++
std::set<int> s;
auto c = std::count(s.begin(), s.end(), 43);
// becomes
auto c = s.count(43);
.. title:: clang-tidy - performance-inefficient-string-concatenation
performance-inefficient-string-concatenation
============================================
This check warns about the performance overhead arising from concatenating
strings using the ``operator+``, for instance:
.. code-block:: c++
std::string a("Foo"), b("Bar");
a = a + b;
Instead of this structure you should use ``operator+=`` or ``std::string``'s
(``std::basic_string``) class member function ``append()``. For instance:
.. code-block:: c++
std::string a("Foo"), b("Baz");
for (int i = 0; i < 20000; ++i) {
a = a + "Bar" + b;
}
Could be rewritten in a greatly more efficient way like:
.. code-block:: c++
std::string a("Foo"), b("Baz");
for (int i = 0; i < 20000; ++i) {
a.append("Bar").append(b);
}
And this can be rewritten too:
.. code-block:: c++
void f(const std::string&) {}
std::string a("Foo"), b("Baz");
void g() {
f(a + "Bar" + b);
}
In a slightly more efficient way like:
.. code-block:: c++
void f(const std::string&) {}
std::string a("Foo"), b("Baz");
void g() {
f(std::string(a).append("Bar").append(b));
}
Options
-------
.. option:: StrictMode
When `false`, the check will only check the string usage in ``while``, ``for``
and ``for-range`` statements. Default is `false`.
.. title:: clang-tidy - performance-inefficient-vector-operation
performance-inefficient-vector-operation
========================================
Finds possible inefficient ``std::vector`` operations (e.g. ``push_back``,
``emplace_back``) that may cause unnecessary memory reallocations.
It can also find calls that add element to protobuf repeated field in a loop
without calling Reserve() before the loop. Calling Reserve() first can avoid
unnecessary memory reallocations.
Currently, the check only detects following kinds of loops with a single
statement body:
* Counter-based for loops start with 0:
.. code-block:: c++
std::vector<int> v;
for (int i = 0; i < n; ++i) {
v.push_back(n);
// This will trigger the warning since the push_back may cause multiple
// memory reallocations in v. This can be avoid by inserting a 'reserve(n)'
// statement before the for statement.
}
SomeProto p;
for (int i = 0; i < n; ++i) {
p.add_xxx(n);
// This will trigger the warning since the add_xxx may cause multiple memory
// reallocations. This can be avoid by inserting a
// 'p.mutable_xxx().Reserve(n)' statement before the for statement.
}
* For-range loops like ``for (range-declaration : range_expression)``, the type
of ``range_expression`` can be ``std::vector``, ``std::array``,
``std::deque``, ``std::set``, ``std::unordered_set``, ``std::map``,
``std::unordered_set``:
.. code-block:: c++
std::vector<int> data;
std::vector<int> v;
for (auto element : data) {
v.push_back(element);
// This will trigger the warning since the 'push_back' may cause multiple
// memory reallocations in v. This can be avoid by inserting a
// 'reserve(data.size())' statement before the for statement.
}
Options
-------
.. option:: VectorLikeClasses
Semicolon-separated list of names of vector-like classes. By default only
``::std::vector`` is considered.
.. option:: EnableProto
When `true`, the check will also warn on inefficient operations for proto
repeated fields. Otherwise, the check only warns on inefficient vector
operations. Default is `false`.
.. title:: clang-tidy - performance-move-const-arg
performance-move-const-arg
==========================
The check warns
- if ``std::move()`` is called with a constant argument,
- if ``std::move()`` is called with an argument of a trivially-copyable type,
- if the result of ``std::move()`` is passed as a const reference argument.
In all three cases, the check will suggest a fix that removes the
``std::move()``.
Here are examples of each of the three cases:
.. code-block:: c++
const string s;
return std::move(s); // Warning: std::move of the const variable has no effect
int x;
return std::move(x); // Warning: std::move of the variable of a trivially-copyable type has no effect
void f(const string &s);
string s;
f(std::move(s)); // Warning: passing result of std::move as a const reference argument; no move will actually happen
Options
-------
.. option:: CheckTriviallyCopyableMove
If `true`, enables detection of trivially copyable types that do not
have a move constructor. Default is `true`.
.. title:: clang-tidy - performance-move-constructor-init
performance-move-constructor-init
=================================
"cert-oop11-cpp" redirects here as an alias for this check.
The check flags user-defined move constructors that have a ctor-initializer
initializing a member or base class through a copy constructor instead of a
move constructor.
.. title:: clang-tidy - performance-no-automatic-move
performance-no-automatic-move
=============================
Finds local variables that cannot be automatically moved due to constness.
Under
`certain conditions <https://en.cppreference.com/w/cpp/language/return#automatic_move_from_local_variables_and_parameters>`_,
local values are automatically moved out when returning from a function. A
common mistake is to declare local ``lvalue`` variables ``const``, which
prevents the move.
Example `[1] <https://godbolt.org/z/x7SYYA>`_:
.. code-block:: c++
StatusOr<std::vector<int>> Cool() {
std::vector<int> obj = ...;
return obj; // calls StatusOr::StatusOr(std::vector<int>&&)
}
StatusOr<std::vector<int>> NotCool() {
const std::vector<int> obj = ...;
return obj; // calls `StatusOr::StatusOr(const std::vector<int>&)`
}
The former version (``Cool``) should be preferred over the latter (``Uncool``)
as it will avoid allocations and potentially large memory copies.
Semantics
---------
In the example above, ``StatusOr::StatusOr(T&&)`` have the same semantics as
long as the copy and move constructors for ``T`` have the same semantics. Note
that there is no guarantee that ``S::S(T&&)`` and ``S::S(const T&)`` have the
same semantics for any single ``S``, so we're not providing automated fixes for
this check, and judgement should be exerted when making the suggested changes.
-Wreturn-std-move
-----------------
Another case where the move cannot happen is the following:
.. code-block:: c++
StatusOr<std::vector<int>> Uncool() {
std::vector<int>&& obj = ...;
return obj; // calls `StatusOr::StatusOr(const std::vector<int>&)`
}
In that case the fix is more consensual: just `return std::move(obj)`.
This is handled by the `-Wreturn-std-move` warning.
.. title:: clang-tidy - performance-no-int-to-ptr
performance-no-int-to-ptr
=========================
Diagnoses every integer to pointer cast.
While casting an (integral) pointer to an integer is obvious - you just get
the integral value of the pointer, casting an integer to an (integral) pointer
is deceivingly different. While you will get a pointer with that integral value,
if you got that integral value via a pointer-to-integer cast originally,
the new pointer will lack the provenance information from the original pointer.
So while (integral) pointer to integer casts are effectively no-ops,
and are transparent to the optimizer, integer to (integral) pointer casts
are *NOT* transparent, and may conceal information from optimizer.
While that may be the intention, it is not always so. For example,
let's take a look at a routine to align the pointer up to the multiple of 16:
The obvious, naive implementation for that is:
.. code-block:: c++
char* src(char* maybe_underbiased_ptr) {
uintptr_t maybe_underbiased_intptr = (uintptr_t)maybe_underbiased_ptr;
uintptr_t aligned_biased_intptr = maybe_underbiased_intptr + 15;
uintptr_t aligned_intptr = aligned_biased_intptr & (~15);
return (char*)aligned_intptr; // warning: avoid integer to pointer casts [performance-no-int-to-ptr]
}
The check will rightfully diagnose that cast.
But when provenance concealment is not the goal of the code, but an accident,
this example can be rewritten as follows, without using integer to pointer cast:
.. code-block:: c++
char*
tgt(char* maybe_underbiased_ptr) {
uintptr_t maybe_underbiased_intptr = (uintptr_t)maybe_underbiased_ptr;
uintptr_t aligned_biased_intptr = maybe_underbiased_intptr + 15;
uintptr_t aligned_intptr = aligned_biased_intptr & (~15);
uintptr_t bias = aligned_intptr - maybe_underbiased_intptr;
return maybe_underbiased_ptr + bias;
}
.. title:: clang-tidy - performance-noexcept-move-constructor
performance-noexcept-move-constructor
=====================================
The check flags user-defined move constructors and assignment operators not
marked with ``noexcept`` or marked with ``noexcept(expr)`` where ``expr``
evaluates to ``false`` (but is not a ``false`` literal itself).
Move constructors of all the types used with STL containers, for example,
need to be declared ``noexcept``. Otherwise STL will choose copy constructors
instead. The same is valid for move assignment operations.
.. title:: clang-tidy - performance-trivially-destructible
performance-trivially-destructible
==================================
Finds types that could be made trivially-destructible by removing out-of-line
defaulted destructor declarations.
.. code-block:: c++
struct A: TrivialType {
~A(); // Makes A non-trivially-destructible.
TrivialType trivial_fields;
};
A::~A() = default;
.. title:: clang-tidy - performance-type-promotion-in-math-fn
performance-type-promotion-in-math-fn
=====================================
Finds calls to C math library functions (from ``math.h`` or, in C++, ``cmath``)
with implicit ``float`` to ``double`` promotions.
For example, warns on ``::sin(0.f)``, because this funciton's parameter is a
double. You probably meant to call ``std::sin(0.f)`` (in C++), or ``sinf(0.f)``
(in C).
.. code-block:: c++
float a;
asin(a);
// becomes
float a;
std::asin(a);
.. title:: clang-tidy - performance-unnecessary-copy-initialization
performance-unnecessary-copy-initialization
===========================================
Finds local variable declarations that are initialized using the copy
constructor of a non-trivially-copyable type but it would suffice to obtain a
const reference.
The check is only applied if it is safe to replace the copy by a const
reference. This is the case when the variable is const qualified or when it is
only used as a const, i.e. only const methods or operators are invoked on it, or
it is used as const reference or value argument in constructors or function
calls.
Example:
.. code-block:: c++
const string& constReference();
void Function() {
// The warning will suggest making this a const reference.
const string UnnecessaryCopy = constReference();
}
struct Foo {
const string& name() const;
};
void Function(const Foo& foo) {
// The warning will suggest making this a const reference.
string UnnecessaryCopy1 = foo.name();
UnnecessaryCopy1.find("bar");
// The warning will suggest making this a const reference.
string UnnecessaryCopy2 = UnnecessaryCopy1;
UnnecessaryCopy2.find("bar");
}
Options
-------
.. option:: AllowedTypes
A semicolon-separated list of names of types allowed to be initialized by
copying. Regular expressions are accepted, e.g. `[Rr]ef(erence)?$` matches
every type with suffix `Ref`, `ref`, `Reference` and `reference`. The default
is empty. If a name in the list contains the sequence `::` it is matched
against the qualified typename (i.e. `namespace::Type`, otherwise it is
matched against only the type name (i.e. `Type`).
.. title:: clang-tidy - performance-unnecessary-value-param
performance-unnecessary-value-param
===================================
Flags value parameter declarations of expensive to copy types that are copied
for each invocation but it would suffice to pass them by const reference.
The check is only applied to parameters of types that are expensive to copy
which means they are not trivially copyable or have a non-trivial copy
constructor or destructor.
To ensure that it is safe to replace the value parameter with a const reference
the following heuristic is employed:
1. the parameter is const qualified;
2. the parameter is not const, but only const methods or operators are invoked
on it, or it is used as const reference or value argument in constructors or
function calls.
Example:
.. code-block:: c++
void f(const string Value) {
// The warning will suggest making Value a reference.
}
void g(ExpensiveToCopy Value) {
// The warning will suggest making Value a const reference.
Value.ConstMethd();
ExpensiveToCopy Copy(Value);
}
If the parameter is not const, only copied or assigned once and has a
non-trivial move-constructor or move-assignment operator respectively the check
will suggest to move it.
Example:
.. code-block:: c++
void setValue(string Value) {
Field = Value;
}
Will become:
.. code-block:: c++
#include <utility>
void setValue(string Value) {
Field = std::move(Value);
}
Options
-------
.. option:: IncludeStyle
A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
.. option:: AllowedTypes
A semicolon-separated list of names of types allowed to be passed by value.
Regular expressions are accepted, e.g. `[Rr]ef(erence)?$` matches every type
with suffix `Ref`, `ref`, `Reference` and `reference`. The default is
empty. If a name in the list contains the sequence `::` it is matched against
the qualified typename (i.e. `namespace::Type`, otherwise it is matched
against only the type name (i.e. `Type`).
.. title:: clang-tidy - portability-restrict-system-includes
portability-restrict-system-includes
====================================
Checks to selectively allow or disallow a configurable list of system headers.
For example:
In order to **only** allow `zlib.h` from the system you would set the options
to `-*,zlib.h`.
.. code-block:: c++
#include <curses.h> // Bad: disallowed system header.
#include <openssl/ssl.h> // Bad: disallowed system header.
#include <zlib.h> // Good: allowed system header.
#include "src/myfile.h" // Good: non-system header always allowed.
In order to allow everything **except** `zlib.h` from the system you would set
the options to `*,-zlib.h`.
.. code-block:: c++
#include <curses.h> // Good: allowed system header.
#include <openssl/ssl.h> // Good: allowed system header.
#include <zlib.h> // Bad: disallowed system header.
#include "src/myfile.h" // Good: non-system header always allowed.
Since the options support globbing you can use wildcarding to allow groups of
headers.
`-*,openssl/*.h` will allow all openssl headers but disallow any others.
.. code-block:: c++
#include <curses.h> // Bad: disallowed system header.
#include <openssl/ssl.h> // Good: allowed system header.
#include <openssl/rsa.h> // Good: allowed system header.
#include <zlib.h> // Bad: disallowed system header.
#include "src/myfile.h" // Good: non-system header always allowed.
Options
-------
.. option:: Includes
A string containing a comma separated glob list of allowed include
filenames. Similar to the -checks glob list for running clang-tidy itself,
the two wildcard characters are `*` and `-`, to include and exclude globs,
respectively. The default is `*`, which allows all includes.
.. title:: clang-tidy - portability-simd-intrinsics
portability-simd-intrinsics
===========================
Finds SIMD intrinsics calls and suggests ``std::experimental::simd`` (`P0214`_)
alternatives.
If the option :option:`Suggest` is set to `true`, for
.. code-block:: c++
_mm_add_epi32(a, b); // x86
vec_add(a, b); // Power
the check suggests an alternative: ``operator+`` on ``std::experimental::simd``
objects.
Otherwise, it just complains the intrinsics are non-portable (and there are
`P0214`_ alternatives).
Many architectures provide SIMD operations (e.g. x86 SSE/AVX, Power AltiVec/VSX,
ARM NEON). It is common that SIMD code implementing the same algorithm, is
written in multiple target-dispatching pieces to optimize for different
architectures or micro-architectures.
The C++ standard proposal `P0214`_ and its extensions cover many common SIMD
operations. By migrating from target-dependent intrinsics to `P0214`_
operations, the SIMD code can be simplified and pieces for different targets can
be unified.
Refer to `P0214`_ for introduction and motivation for the data-parallel standard
library.
Options
-------
.. option:: Suggest
If this option is set to `true` (default is `false`), the check will suggest
`P0214`_ alternatives, otherwise it only points out the intrinsic function is
non-portable.
.. option:: Std
The namespace used to suggest `P0214`_ alternatives. If not specified, `std::`
for `-std=c++20` and `std::experimental::` for `-std=c++11`.
.. _P0214: https://wg21.link/p0214
.. title:: clang-tidy - readability-avoid-const-params-in-decls
readability-avoid-const-params-in-decls
=======================================
Checks whether a function declaration has parameters that are top level
``const``.
``const`` values in declarations do not affect the signature of a function, so
they should not be put there.
Examples:
.. code-block:: c++
void f(const string); // Bad: const is top level.
void f(const string&); // Good: const is not top level.
.. title:: clang-tidy - readability-braces-around-statements
readability-braces-around-statements
====================================
`google-readability-braces-around-statements` redirects here as an alias for
this check.
Checks that bodies of ``if`` statements and loops (``for``, ``do while``, and
``while``) are inside braces.
Before:
.. code-block:: c++
if (condition)
statement;
After:
.. code-block:: c++
if (condition) {
statement;
}
Options
-------
.. option:: ShortStatementLines
Defines the minimal number of lines that the statement should have in order
to trigger this check.
The number of lines is counted from the end of condition or initial keyword
(``do``/``else``) until the last line of the inner statement. Default value
`0` means that braces will be added to all statements (not having them
already).
.. title:: clang-tidy - readability-const-return-type
readability-const-return-type
=============================
Checks for functions with a ``const``-qualified return type and recommends
removal of the ``const`` keyword. Such use of `const` is usually superfluous,
and can prevent valuable compiler optimizations. Does not (yet) fix trailing
return types.
Examples:
.. code-block:: c++
const int foo();
const Clazz foo();
Clazz *const foo();
Note that this applies strictly to top-level qualification, which excludes
pointers or references to const values. For example, these are fine:
.. code-block:: c++
const int* foo();
const int& foo();
const Clazz* foo();
.. title:: clang-tidy - readability-container-size-empty
readability-container-size-empty
================================
Checks whether a call to the ``size()`` method can be replaced with a call to
``empty()``.
The emptiness of a container should be checked using the ``empty()`` method
instead of the ``size()`` method. It is not guaranteed that ``size()`` is a
constant-time function, and it is generally more efficient and also shows
clearer intent to use ``empty()``. Furthermore some containers may implement
the ``empty()`` method but not implement the ``size()`` method. Using
``empty()`` whenever possible makes it easier to switch to another container in
the future.
The check issues warning if a container has ``size()`` and ``empty()`` methods
matching following signatures:
.. code-block:: c++
size_type size() const;
bool empty() const;
`size_type` can be any kind of integer type.
.. title:: clang-tidy - readability-convert-member-functions-to-static
readability-convert-member-functions-to-static
==============================================
Finds non-static member functions that can be made ``static``
because the functions don't use ``this``.
After applying modifications as suggested by the check, running the check again
might find more opportunities to mark member functions ``static``.
After making a member function ``static``, you might want to run the check
`readability-static-accessed-through-instance <readability-static-accessed-through-instance.html>`_ to replace calls like
``Instance.method()`` by ``Class::method()``.
.. title:: clang-tidy - readability-delete-null-pointer
readability-delete-null-pointer
===============================
Checks the ``if`` statements where a pointer's existence is checked and then deletes the pointer.
The check is unnecessary as deleting a null pointer has no effect.
.. code:: c++
int *p;
if (p)
delete p;
.. title:: clang-tidy - readability-else-after-return
readability-else-after-return
=============================
`LLVM Coding Standards <https://llvm.org/docs/CodingStandards.html>`_ advises to
reduce indentation where possible and where it makes understanding code easier.
Early exit is one of the suggested enforcements of that. Please do not use
``else`` or ``else if`` after something that interrupts control flow - like
``return``, ``break``, ``continue``, ``throw``.
The following piece of code illustrates how the check works. This piece of code:
.. code-block:: c++
void foo(int Value) {
int Local = 0;
for (int i = 0; i < 42; i++) {
if (Value == 1) {
return;
} else {
Local++;
}
if (Value == 2)
continue;
else
Local++;
if (Value == 3) {
throw 42;
} else {
Local++;
}
}
}
Would be transformed into:
.. code-block:: c++
void foo(int Value) {
int Local = 0;
for (int i = 0; i < 42; i++) {
if (Value == 1) {
return;
}
Local++;
if (Value == 2)
continue;
Local++;
if (Value == 3) {
throw 42;
}
Local++;
}
}
Options
-------
.. option:: WarnOnUnfixable
When `true`, emit a warning for cases where the check can't output a
Fix-It. These can occur with declarations inside the ``else`` branch that
would have an extended lifetime if the ``else`` branch was removed.
Default value is `true`.
.. option:: WarnOnConditionVariables
When `true`, the check will attempt to refactor a variable defined inside
the condition of the ``if`` statement that is used in the ``else`` branch
defining them just before the ``if`` statement. This can only be done if
the ``if`` statement is the last statement in its parents scope.
Default value is `true`.
LLVM alias
----------
There is an alias of this check called llvm-else-after-return.
In that version the options :option:`WarnOnUnfixable` and
:option:`WarnOnConditionVariables` are both set to `false` by default.
This check helps to enforce this `LLVM Coding Standards recommendation
<https://llvm.org/docs/CodingStandards.html#don-t-use-else-after-a-return>`_.
.. title:: clang-tidy - readability-function-cognitive-complexity
readability-function-cognitive-complexity
=========================================
Checks function Cognitive Complexity metric.
The metric is implemented as per the `COGNITIVE COMPLEXITY by SonarSource
<https://www.sonarsource.com/docs/CognitiveComplexity.pdf>`_ specification
version 1.2 (19 April 2017).
Options
-------
.. option:: Threshold
Flag functions with Cognitive Complexity exceeding this number.
The default is `25`.
.. option:: DescribeBasicIncrements
If set to `true`, then for each function exceeding the complexity threshold
the check will issue additional diagnostics on every piece of code (loop,
`if` statement, etc.) which contributes to that complexity. See also the
examples below. Default is `true`.
.. option:: IgnoreMacros
If set to `true`, the check will ignore code inside macros. Note, that also
any macro arguments are ignored, even if they should count to the complexity.
As this might change in the future, this option isn't guaranteed to be
forward-compatible. Default is `false`.
Building blocks
---------------
There are three basic building blocks of a Cognitive Complexity metric:
Increment
^^^^^^^^^
The following structures increase the function's Cognitive Complexity metric
(by `1`):
* Conditional operators:
- ``if()``
- ``else if()``
- ``else``
- ``cond ? true : false``
* ``switch()``
* Loops:
- ``for()``
- C++11 range-based ``for()``
- ``while()``
- ``do while()``
* ``catch ()``
* ``goto LABEL``, ``goto *(&&LABEL))``,
* sequences of binary logical operators:
- ``boolean1 || boolean2``
- ``boolean1 && boolean2``
Nesting level
^^^^^^^^^^^^^
While by itself the nesting level not change the function's Cognitive Complexity
metric, it is tracked, and is used by the next, third building block.
The following structures increase the nesting level (by `1`):
* Conditional operators:
- ``if()``
- ``else if()``
- ``else``
- ``cond ? true : false``
* ``switch()``
* Loops:
- ``for()``
- C++11 range-based ``for()``
- ``while()``
- ``do while()``
* ``catch ()``
* Nested functions:
- C++11 Lambda
- Nested ``class``
- Nested ``struct``
* GNU statement expression
* Apple Block Declaration
Nesting increment
^^^^^^^^^^^^^^^^^
This is where the previous basic building block, `Nesting level`_, matters.
The following structures increase the function's Cognitive Complexity metric by
the current `Nesting level`_:
* Conditional operators:
- ``if()``
- ``cond ? true : false``
* ``switch()``
* Loops:
- ``for()``
- C++11 range-based ``for()``
- ``while()``
- ``do while()``
* ``catch ()``
Examples
--------
The simplest case. This function has Cognitive Complexity of `0`.
.. code-block:: c++
void function0() {}
Slightly better example. This function has Cognitive Complexity of `1`.
.. code-block:: c++
int function1(bool var) {
if(var) // +1, nesting level +1
return 42;
return 0;
}
Full example. This function has Cognitive Complexity of `3`.
.. code-block:: c++
int function3(bool var1, bool var2) {
if(var1) { // +1, nesting level +1
if(var2) // +2 (1 + current nesting level of 1), nesting level +1
return 42;
}
return 0;
}
In the last example, the check will flag `function3` if the option Threshold is
set to `2` or smaller. If the option DescribeBasicIncrements is set to `true`,
it will additionally flag the two `if` statements with the amounts by which they
increase to the complexity of the function and the current nesting level.
Limitations
-----------
The metric is implemented with two notable exceptions:
* `preprocessor conditionals` (``#ifdef``, ``#if``, ``#elif``, ``#else``,
``#endif``) are not accounted for.
* `each method in a recursion cycle` is not accounted for. It can't be fully
implemented, because cross-translational-unit analysis would be needed,
which is currently not possible in clang-tidy.
.. title:: clang-tidy - readability-function-size
readability-function-size
=========================
`google-readability-function-size` redirects here as an alias for this check.
Checks for large functions based on various metrics.
Options
-------
.. option:: LineThreshold
Flag functions exceeding this number of lines. The default is `-1` (ignore
the number of lines).
.. option:: StatementThreshold
Flag functions exceeding this number of statements. This may differ
significantly from the number of lines for macro-heavy code. The default is
`800`.
.. option:: BranchThreshold
Flag functions exceeding this number of control statements. The default is
`-1` (ignore the number of branches).
.. option:: ParameterThreshold
Flag functions that exceed a specified number of parameters. The default
is `-1` (ignore the number of parameters).
.. option:: NestingThreshold
Flag compound statements which create next nesting level after
`NestingThreshold`. This may differ significantly from the expected value
for macro-heavy code. The default is `-1` (ignore the nesting level).
.. option:: VariableThreshold
Flag functions exceeding this number of variables declared in the body.
The default is `-1` (ignore the number of variables).
Please note that function parameters and variables declared in lambdas,
GNU Statement Expressions, and nested class inline functions are not counted.
.. title:: clang-tidy - readability-identifier-naming
readability-identifier-naming
=============================
Checks for identifiers naming style mismatch.
This check will try to enforce coding guidelines on the identifiers naming. It
supports one of the following casing types and tries to convert from one to
another if a mismatch is detected
Casing types include:
- ``lower_case``,
- ``UPPER_CASE``,
- ``camelBack``,
- ``CamelCase``,
- ``camel_Snake_Back``,
- ``Camel_Snake_Case``,
- ``aNy_CasE``.
It also supports a fixed prefix and suffix that will be prepended or appended
to the identifiers, regardless of the casing.
Many configuration options are available, in order to be able to create
different rules for different kinds of identifiers. In general, the rules are
falling back to a more generic rule if the specific case is not configured.
The naming of virtual methods is reported where they occur in the base class,
but not where they are overridden, as it can't be fixed locally there.
This also applies for pseudo-override patterns like CRTP.
Options
-------
The following options are describe below:
- :option:`AbstractClassCase`, :option:`AbstractClassPrefix`, :option:`AbstractClassSuffix`, :option:`AbstractClassIgnoredRegexp`
- :option:`AggressiveDependentMemberLookup`
- :option:`ClassCase`, :option:`ClassPrefix`, :option:`ClassSuffix`, :option:`ClassIgnoredRegexp`
- :option:`ClassConstantCase`, :option:`ClassConstantPrefix`, :option:`ClassConstantSuffix`, :option:`ClassConstantIgnoredRegexp`
- :option:`ClassMemberCase`, :option:`ClassMemberPrefix`, :option:`ClassMemberSuffix`, :option:`ClassMemberIgnoredRegexp`
- :option:`ClassMethodCase`, :option:`ClassMethodPrefix`, :option:`ClassMethodSuffix`, :option:`ClassMethodIgnoredRegexp`
- :option:`ConstantCase`, :option:`ConstantPrefix`, :option:`ConstantSuffix`, :option:`ConstantIgnoredRegexp`
- :option:`ConstantMemberCase`, :option:`ConstantMemberPrefix`, :option:`ConstantMemberSuffix`, :option:`ConstantMemberIgnoredRegexp`
- :option:`ConstantParameterCase`, :option:`ConstantParameterPrefix`, :option:`ConstantParameterSuffix`, :option:`ConstantParameterIgnoredRegexp`
- :option:`ConstantPointerParameterCase`, :option:`ConstantPointerParameterPrefix`, :option:`ConstantPointerParameterSuffix`, :option:`ConstantPointerParameterIgnoredRegexp`
- :option:`ConstexprFunctionCase`, :option:`ConstexprFunctionPrefix`, :option:`ConstexprFunctionSuffix`, :option:`ConstexprFunctionIgnoredRegexp`
- :option:`ConstexprMethodCase`, :option:`ConstexprMethodPrefix`, :option:`ConstexprMethodSuffix`, :option:`ConstexprMethodIgnoredRegexp`
- :option:`ConstexprVariableCase`, :option:`ConstexprVariablePrefix`, :option:`ConstexprVariableSuffix`, :option:`ConstexprVariableIgnoredRegexp`
- :option:`EnumCase`, :option:`EnumPrefix`, :option:`EnumSuffix`, :option:`EnumIgnoredRegexp`
- :option:`EnumConstantCase`, :option:`EnumConstantPrefix`, :option:`EnumConstantSuffix`, :option:`EnumConstantIgnoredRegexp`
- :option:`FunctionCase`, :option:`FunctionPrefix`, :option:`FunctionSuffix`, :option:`FunctionIgnoredRegexp`
- :option:`GetConfigPerFile`
- :option:`GlobalConstantCase`, :option:`GlobalConstantPrefix`, :option:`GlobalConstantSuffix`, :option:`GlobalConstantIgnoredRegexp`
- :option:`GlobalConstantPointerCase`, :option:`GlobalConstantPointerPrefix`, :option:`GlobalConstantPointerSuffix`, :option:`GlobalConstantPointerIgnoredRegexp`
- :option:`GlobalFunctionCase`, :option:`GlobalFunctionPrefix`, :option:`GlobalFunctionSuffix`, :option:`GlobalFunctionIgnoredRegexp`
- :option:`GlobalPointerCase`, :option:`GlobalPointerPrefix`, :option:`GlobalPointerSuffix`, :option:`GlobalPointerIgnoredRegexp`
- :option:`GlobalVariableCase`, :option:`GlobalVariablePrefix`, :option:`GlobalVariableSuffix`, :option:`GlobalVariableIgnoredRegexp`
- :option:`IgnoreMainLikeFunctions`
- :option:`InlineNamespaceCase`, :option:`InlineNamespacePrefix`, :option:`InlineNamespaceSuffix`, :option:`InlineNamespaceIgnoredRegexp`
- :option:`LocalConstantCase`, :option:`LocalConstantPrefix`, :option:`LocalConstantSuffix`, :option:`LocalConstantIgnoredRegexp`
- :option:`LocalConstantPointerCase`, :option:`LocalConstantPointerPrefix`, :option:`LocalConstantPointerSuffix`, :option:`LocalConstantPointerIgnoredRegexp`
- :option:`LocalPointerCase`, :option:`LocalPointerPrefix`, :option:`LocalPointerSuffix`, :option:`LocalPointerIgnoredRegexp`
- :option:`LocalVariableCase`, :option:`LocalVariablePrefix`, :option:`LocalVariableSuffix`, :option:`LocalVariableIgnoredRegexp`
- :option:`MacroDefinitionCase`, :option:`MacroDefinitionPrefix`, :option:`MacroDefinitionSuffix`, :option:`MacroDefinitionIgnoredRegexp`
- :option:`MemberCase`, :option:`MemberPrefix`, :option:`MemberSuffix`, :option:`MemberIgnoredRegexp`
- :option:`MethodCase`, :option:`MethodPrefix`, :option:`MethodSuffix`, :option:`MethodIgnoredRegexp`
- :option:`NamespaceCase`, :option:`NamespacePrefix`, :option:`NamespaceSuffix`, :option:`NamespaceIgnoredRegexp`
- :option:`ParameterCase`, :option:`ParameterPrefix`, :option:`ParameterSuffix`, :option:`ParameterIgnoredRegexp`
- :option:`ParameterPackCase`, :option:`ParameterPackPrefix`, :option:`ParameterPackSuffix`, :option:`ParameterPackIgnoredRegexp`
- :option:`PointerParameterCase`, :option:`PointerParameterPrefix`, :option:`PointerParameterSuffix`, :option:`PointerParameterIgnoredRegexp`
- :option:`PrivateMemberCase`, :option:`PrivateMemberPrefix`, :option:`PrivateMemberSuffix`, :option:`PrivateMemberIgnoredRegexp`
- :option:`PrivateMethodCase`, :option:`PrivateMethodPrefix`, :option:`PrivateMethodSuffix`, :option:`PrivateMethodIgnoredRegexp`
- :option:`ProtectedMemberCase`, :option:`ProtectedMemberPrefix`, :option:`ProtectedMemberSuffix`, :option:`ProtectedMemberIgnoredRegexp`
- :option:`ProtectedMethodCase`, :option:`ProtectedMethodPrefix`, :option:`ProtectedMethodSuffix`, :option:`ProtectedMethodIgnoredRegexp`
- :option:`PublicMemberCase`, :option:`PublicMemberPrefix`, :option:`PublicMemberSuffix`, :option:`PublicMemberIgnoredRegexp`
- :option:`PublicMethodCase`, :option:`PublicMethodPrefix`, :option:`PublicMethodSuffix`, :option:`PublicMethodIgnoredRegexp`
- :option:`ScopedEnumConstantCase`, :option:`ScopedEnumConstantPrefix`, :option:`ScopedEnumConstantSuffix`, :option:`ScopedEnumConstantIgnoredRegexp`
- :option:`StaticConstantCase`, :option:`StaticConstantPrefix`, :option:`StaticConstantSuffix`, :option:`StaticConstantIgnoredRegexp`
- :option:`StaticVariableCase`, :option:`StaticVariablePrefix`, :option:`StaticVariableSuffix`, :option:`StaticVariableIgnoredRegexp`
- :option:`StructCase`, :option:`StructPrefix`, :option:`StructSuffix`, :option:`StructIgnoredRegexp`
- :option:`TemplateParameterCase`, :option:`TemplateParameterPrefix`, :option:`TemplateParameterSuffix`, :option:`TemplateParameterIgnoredRegexp`
- :option:`TemplateTemplateParameterCase`, :option:`TemplateTemplateParameterPrefix`, :option:`TemplateTemplateParameterSuffix`, :option:`TemplateTemplateParameterIgnoredRegexp`
- :option:`TypeAliasCase`, :option:`TypeAliasPrefix`, :option:`TypeAliasSuffix`, :option:`TypeAliasIgnoredRegexp`
- :option:`TypedefCase`, :option:`TypedefPrefix`, :option:`TypedefSuffix`, :option:`TypedefIgnoredRegexp`
- :option:`TypeTemplateParameterCase`, :option:`TypeTemplateParameterPrefix`, :option:`TypeTemplateParameterSuffix`, :option:`TypeTemplateParameterIgnoredRegexp`
- :option:`UnionCase`, :option:`UnionPrefix`, :option:`UnionSuffix`, :option:`UnionIgnoredRegexp`
- :option:`ValueTemplateParameterCase`, :option:`ValueTemplateParameterPrefix`, :option:`ValueTemplateParameterSuffix`, :option:`ValueTemplateParameterIgnoredRegexp`
- :option:`VariableCase`, :option:`VariablePrefix`, :option:`VariableSuffix`, :option:`VariableIgnoredRegexp`
- :option:`VirtualMethodCase`, :option:`VirtualMethodPrefix`, :option:`VirtualMethodSuffix`, :option:`VirtualMethodIgnoredRegexp`
.. option:: AbstractClassCase
When defined, the check will ensure abstract class names conform to the
selected casing.
.. option:: AbstractClassPrefix
When defined, the check will ensure abstract class names will add the
prefixed with the given value (regardless of casing).
.. option:: AbstractClassIgnoredRegexp
Identifier naming checks won't be enforced for abstract class names
matching this regular expression.
.. option:: AbstractClassSuffix
When defined, the check will ensure abstract class names will add the
suffix with the given value (regardless of casing).
For example using values of:
- AbstractClassCase of ``lower_case``
- AbstractClassPrefix of ``pre_``
- AbstractClassSuffix of ``_post``
Identifies and/or transforms abstract class names as follows:
Before:
.. code-block:: c++
class ABSTRACT_CLASS {
public:
ABSTRACT_CLASS();
};
After:
.. code-block:: c++
class pre_abstract_class_post {
public:
pre_abstract_class_post();
};
.. option:: AggressiveDependentMemberLookup
When set to `true` the check will look in dependent base classes for dependent
member references that need changing. This can lead to errors with template
specializations so the default value is `false`.
For example using values of:
- ClassMemberCase of ``lower_case``
Before:
.. code-block:: c++
template <typename T>
struct Base {
T BadNamedMember;
};
template <typename T>
struct Derived : Base<T> {
void reset() {
this->BadNamedMember = 0;
}
};
After if AggressiveDependentMemberLookup is `false`:
.. code-block:: c++
template <typename T>
struct Base {
T bad_named_member;
};
template <typename T>
struct Derived : Base<T> {
void reset() {
this->BadNamedMember = 0;
}
};
After if AggressiveDependentMemberLookup is `true`:
.. code-block:: c++
template <typename T>
struct Base {
T bad_named_member;
};
template <typename T>
struct Derived : Base<T> {
void reset() {
this->bad_named_member = 0;
}
};
.. option:: ClassCase
When defined, the check will ensure class names conform to the
selected casing.
.. option:: ClassPrefix
When defined, the check will ensure class names will add the
prefixed with the given value (regardless of casing).
.. option:: ClassIgnoredRegexp
Identifier naming checks won't be enforced for class names matching
this regular expression.
.. option:: ClassSuffix
When defined, the check will ensure class names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ClassCase of ``lower_case``
- ClassPrefix of ``pre_``
- ClassSuffix of ``_post``
Identifies and/or transforms class names as follows:
Before:
.. code-block:: c++
class FOO {
public:
FOO();
~FOO();
};
After:
.. code-block:: c++
class pre_foo_post {
public:
pre_foo_post();
~pre_foo_post();
};
.. option:: ClassConstantCase
When defined, the check will ensure class constant names conform to the
selected casing.
.. option:: ClassConstantPrefix
When defined, the check will ensure class constant names will add the
prefixed with the given value (regardless of casing).
.. option:: ClassConstantIgnoredRegexp
Identifier naming checks won't be enforced for class constant names
matching this regular expression.
.. option:: ClassConstantSuffix
When defined, the check will ensure class constant names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ClassConstantCase of ``lower_case``
- ClassConstantPrefix of ``pre_``
- ClassConstantSuffix of ``_post``
Identifies and/or transforms class constant names as follows:
Before:
.. code-block:: c++
class FOO {
public:
static const int CLASS_CONSTANT;
};
After:
.. code-block:: c++
class FOO {
public:
static const int pre_class_constant_post;
};
.. option:: ClassMemberCase
When defined, the check will ensure class member names conform to the
selected casing.
.. option:: ClassMemberPrefix
When defined, the check will ensure class member names will add the
prefixed with the given value (regardless of casing).
.. option:: ClassMemberIgnoredRegexp
Identifier naming checks won't be enforced for class member names
matching this regular expression.
.. option:: ClassMemberSuffix
When defined, the check will ensure class member names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ClassMemberCase of ``lower_case``
- ClassMemberPrefix of ``pre_``
- ClassMemberSuffix of ``_post``
Identifies and/or transforms class member names as follows:
Before:
.. code-block:: c++
class FOO {
public:
static int CLASS_CONSTANT;
};
After:
.. code-block:: c++
class FOO {
public:
static int pre_class_constant_post;
};
.. option:: ClassMethodCase
When defined, the check will ensure class method names conform to the
selected casing.
.. option:: ClassMethodPrefix
When defined, the check will ensure class method names will add the
prefixed with the given value (regardless of casing).
.. option:: ClassMethodIgnoredRegexp
Identifier naming checks won't be enforced for class method names
matching this regular expression.
.. option:: ClassMethodSuffix
When defined, the check will ensure class method names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ClassMethodCase of ``lower_case``
- ClassMethodPrefix of ``pre_``
- ClassMethodSuffix of ``_post``
Identifies and/or transforms class method names as follows:
Before:
.. code-block:: c++
class FOO {
public:
int CLASS_MEMBER();
};
After:
.. code-block:: c++
class FOO {
public:
int pre_class_member_post();
};
.. option:: ConstantCase
When defined, the check will ensure constant names conform to the
selected casing.
.. option:: ConstantPrefix
When defined, the check will ensure constant names will add the
prefixed with the given value (regardless of casing).
.. option:: ConstantIgnoredRegexp
Identifier naming checks won't be enforced for constant names
matching this regular expression.
.. option:: ConstantSuffix
When defined, the check will ensure constant names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ConstantCase of ``lower_case``
- ConstantPrefix of ``pre_``
- ConstantSuffix of ``_post``
Identifies and/or transforms constant names as follows:
Before:
.. code-block:: c++
void function() { unsigned const MyConst_array[] = {1, 2, 3}; }
After:
.. code-block:: c++
void function() { unsigned const pre_myconst_array_post[] = {1, 2, 3}; }
.. option:: ConstantMemberCase
When defined, the check will ensure constant member names conform to the
selected casing.
.. option:: ConstantMemberPrefix
When defined, the check will ensure constant member names will add the
prefixed with the given value (regardless of casing).
.. option:: ConstantMemberIgnoredRegexp
Identifier naming checks won't be enforced for constant member names
matching this regular expression.
.. option:: ConstantMemberSuffix
When defined, the check will ensure constant member names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ConstantMemberCase of ``lower_case``
- ConstantMemberPrefix of ``pre_``
- ConstantMemberSuffix of ``_post``
Identifies and/or transforms constant member names as follows:
Before:
.. code-block:: c++
class Foo {
char const MY_ConstMember_string[4] = "123";
}
After:
.. code-block:: c++
class Foo {
char const pre_my_constmember_string_post[4] = "123";
}
.. option:: ConstantParameterCase
When defined, the check will ensure constant parameter names conform to the
selected casing.
.. option:: ConstantParameterPrefix
When defined, the check will ensure constant parameter names will add the
prefixed with the given value (regardless of casing).
.. option:: ConstantParameterIgnoredRegexp
Identifier naming checks won't be enforced for constant parameter names
matching this regular expression.
.. option:: ConstantParameterSuffix
When defined, the check will ensure constant parameter names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ConstantParameterCase of ``lower_case``
- ConstantParameterPrefix of ``pre_``
- ConstantParameterSuffix of ``_post``
Identifies and/or transforms constant parameter names as follows:
Before:
.. code-block:: c++
void GLOBAL_FUNCTION(int PARAMETER_1, int const CONST_parameter);
After:
.. code-block:: c++
void GLOBAL_FUNCTION(int PARAMETER_1, int const pre_const_parameter_post);
.. option:: ConstantPointerParameterCase
When defined, the check will ensure constant pointer parameter names conform to the
selected casing.
.. option:: ConstantPointerParameterPrefix
When defined, the check will ensure constant pointer parameter names will add the
prefixed with the given value (regardless of casing).
.. option:: ConstantPointerParameterIgnoredRegexp
Identifier naming checks won't be enforced for constant pointer parameter
names matching this regular expression.
.. option:: ConstantPointerParameterSuffix
When defined, the check will ensure constant pointer parameter names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ConstantPointerParameterCase of ``lower_case``
- ConstantPointerParameterPrefix of ``pre_``
- ConstantPointerParameterSuffix of ``_post``
Identifies and/or transforms constant pointer parameter names as follows:
Before:
.. code-block:: c++
void GLOBAL_FUNCTION(int const *CONST_parameter);
After:
.. code-block:: c++
void GLOBAL_FUNCTION(int const *pre_const_parameter_post);
.. option:: ConstexprFunctionCase
When defined, the check will ensure constexpr function names conform to the
selected casing.
.. option:: ConstexprFunctionPrefix
When defined, the check will ensure constexpr function names will add the
prefixed with the given value (regardless of casing).
.. option:: ConstexprFunctionIgnoredRegexp
Identifier naming checks won't be enforced for constexpr function names
matching this regular expression.
.. option:: ConstexprFunctionSuffix
When defined, the check will ensure constexpr function names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ConstexprFunctionCase of ``lower_case``
- ConstexprFunctionPrefix of ``pre_``
- ConstexprFunctionSuffix of ``_post``
Identifies and/or transforms constexpr function names as follows:
Before:
.. code-block:: c++
constexpr int CE_function() { return 3; }
After:
.. code-block:: c++
constexpr int pre_ce_function_post() { return 3; }
.. option:: ConstexprMethodCase
When defined, the check will ensure constexpr method names conform to the
selected casing.
.. option:: ConstexprMethodPrefix
When defined, the check will ensure constexpr method names will add the
prefixed with the given value (regardless of casing).
.. option:: ConstexprMethodIgnoredRegexp
Identifier naming checks won't be enforced for constexpr method names
matching this regular expression.
.. option:: ConstexprMethodSuffix
When defined, the check will ensure constexpr method names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ConstexprMethodCase of ``lower_case``
- ConstexprMethodPrefix of ``pre_``
- ConstexprMethodSuffix of ``_post``
Identifies and/or transforms constexpr method names as follows:
Before:
.. code-block:: c++
class Foo {
public:
constexpr int CST_expr_Method() { return 2; }
}
After:
.. code-block:: c++
class Foo {
public:
constexpr int pre_cst_expr_method_post() { return 2; }
}
.. option:: ConstexprVariableCase
When defined, the check will ensure constexpr variable names conform to the
selected casing.
.. option:: ConstexprVariablePrefix
When defined, the check will ensure constexpr variable names will add the
prefixed with the given value (regardless of casing).
.. option:: ConstexprVariableIgnoredRegexp
Identifier naming checks won't be enforced for constexpr variable names
matching this regular expression.
.. option:: ConstexprVariableSuffix
When defined, the check will ensure constexpr variable names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ConstexprVariableCase of ``lower_case``
- ConstexprVariablePrefix of ``pre_``
- ConstexprVariableSuffix of ``_post``
Identifies and/or transforms constexpr variable names as follows:
Before:
.. code-block:: c++
constexpr int ConstExpr_variable = MyConstant;
After:
.. code-block:: c++
constexpr int pre_constexpr_variable_post = MyConstant;
.. option:: EnumCase
When defined, the check will ensure enumeration names conform to the
selected casing.
.. option:: EnumPrefix
When defined, the check will ensure enumeration names will add the
prefixed with the given value (regardless of casing).
.. option:: EnumIgnoredRegexp
Identifier naming checks won't be enforced for enumeration names
matching this regular expression.
.. option:: EnumSuffix
When defined, the check will ensure enumeration names will add the
suffix with the given value (regardless of casing).
For example using values of:
- EnumCase of ``lower_case``
- EnumPrefix of ``pre_``
- EnumSuffix of ``_post``
Identifies and/or transforms enumeration names as follows:
Before:
.. code-block:: c++
enum FOO { One, Two, Three };
After:
.. code-block:: c++
enum pre_foo_post { One, Two, Three };
.. option:: EnumConstantCase
When defined, the check will ensure enumeration constant names conform to the
selected casing.
.. option:: EnumConstantPrefix
When defined, the check will ensure enumeration constant names will add the
prefixed with the given value (regardless of casing).
.. option:: EnumConstantIgnoredRegexp
Identifier naming checks won't be enforced for enumeration constant names
matching this regular expression.
.. option:: EnumConstantSuffix
When defined, the check will ensure enumeration constant names will add the
suffix with the given value (regardless of casing).
For example using values of:
- EnumConstantCase of ``lower_case``
- EnumConstantPrefix of ``pre_``
- EnumConstantSuffix of ``_post``
Identifies and/or transforms enumeration constant names as follows:
Before:
.. code-block:: c++
enum FOO { One, Two, Three };
After:
.. code-block:: c++
enum FOO { pre_One_post, pre_Two_post, pre_Three_post };
.. option:: FunctionCase
When defined, the check will ensure function names conform to the
selected casing.
.. option:: FunctionPrefix
When defined, the check will ensure function names will add the
prefixed with the given value (regardless of casing).
.. option:: FunctionIgnoredRegexp
Identifier naming checks won't be enforced for function names
matching this regular expression.
.. option:: FunctionSuffix
When defined, the check will ensure function names will add the
suffix with the given value (regardless of casing).
For example using values of:
- FunctionCase of ``lower_case``
- FunctionPrefix of ``pre_``
- FunctionSuffix of ``_post``
Identifies and/or transforms function names as follows:
Before:
.. code-block:: c++
char MY_Function_string();
After:
.. code-block:: c++
char pre_my_function_string_post();
.. option:: GetConfigPerFile
When `true` the check will look for the configuration for where an
identifier is declared. Useful for when included header files use a
different style.
Default value is `true`.
.. option:: GlobalConstantCase
When defined, the check will ensure global constant names conform to the
selected casing.
.. option:: GlobalConstantPrefix
When defined, the check will ensure global constant names will add the
prefixed with the given value (regardless of casing).
.. option:: GlobalConstantIgnoredRegexp
Identifier naming checks won't be enforced for global constant names
matching this regular expression.
.. option:: GlobalConstantSuffix
When defined, the check will ensure global constant names will add the
suffix with the given value (regardless of casing).
For example using values of:
- GlobalConstantCase of ``lower_case``
- GlobalConstantPrefix of ``pre_``
- GlobalConstantSuffix of ``_post``
Identifies and/or transforms global constant names as follows:
Before:
.. code-block:: c++
unsigned const MyConstGlobal_array[] = {1, 2, 3};
After:
.. code-block:: c++
unsigned const pre_myconstglobal_array_post[] = {1, 2, 3};
.. option:: GlobalConstantPointerCase
When defined, the check will ensure global constant pointer names conform to the
selected casing.
.. option:: GlobalConstantPointerPrefix
When defined, the check will ensure global constant pointer names will add the
prefixed with the given value (regardless of casing).
.. option:: GlobalConstantPointerIgnoredRegexp
Identifier naming checks won't be enforced for global constant pointer
names matching this regular expression.
.. option:: GlobalConstantPointerSuffix
When defined, the check will ensure global constant pointer names will add the
suffix with the given value (regardless of casing).
For example using values of:
- GlobalConstantPointerCase of ``lower_case``
- GlobalConstantPointerPrefix of ``pre_``
- GlobalConstantPointerSuffix of ``_post``
Identifies and/or transforms global constant pointer names as follows:
Before:
.. code-block:: c++
int *const MyConstantGlobalPointer = nullptr;
After:
.. code-block:: c++
int *const pre_myconstantglobalpointer_post = nullptr;
.. option:: GlobalFunctionCase
When defined, the check will ensure global function names conform to the
selected casing.
.. option:: GlobalFunctionPrefix
When defined, the check will ensure global function names will add the
prefixed with the given value (regardless of casing).
.. option:: GlobalFunctionIgnoredRegexp
Identifier naming checks won't be enforced for global function names
matching this regular expression.
.. option:: GlobalFunctionSuffix
When defined, the check will ensure global function names will add the
suffix with the given value (regardless of casing).
For example using values of:
- GlobalFunctionCase of ``lower_case``
- GlobalFunctionPrefix of ``pre_``
- GlobalFunctionSuffix of ``_post``
Identifies and/or transforms global function names as follows:
Before:
.. code-block:: c++
void GLOBAL_FUNCTION(int PARAMETER_1, int const CONST_parameter);
After:
.. code-block:: c++
void pre_global_function_post(int PARAMETER_1, int const CONST_parameter);
.. option:: GlobalPointerCase
When defined, the check will ensure global pointer names conform to the
selected casing.
.. option:: GlobalPointerPrefix
When defined, the check will ensure global pointer names will add the
prefixed with the given value (regardless of casing).
.. option:: GlobalPointerIgnoredRegexp
Identifier naming checks won't be enforced for global pointer names
matching this regular expression.
.. option:: GlobalPointerSuffix
When defined, the check will ensure global pointer names will add the
suffix with the given value (regardless of casing).
For example using values of:
- GlobalPointerCase of ``lower_case``
- GlobalPointerPrefix of ``pre_``
- GlobalPointerSuffix of ``_post``
Identifies and/or transforms global pointer names as follows:
Before:
.. code-block:: c++
int *GLOBAL3;
After:
.. code-block:: c++
int *pre_global3_post;
.. option:: GlobalVariableCase
When defined, the check will ensure global variable names conform to the
selected casing.
.. option:: GlobalVariablePrefix
When defined, the check will ensure global variable names will add the
prefixed with the given value (regardless of casing).
.. option:: GlobalVariableIgnoredRegexp
Identifier naming checks won't be enforced for global variable names
matching this regular expression.
.. option:: GlobalVariableSuffix
When defined, the check will ensure global variable names will add the
suffix with the given value (regardless of casing).
For example using values of:
- GlobalVariableCase of ``lower_case``
- GlobalVariablePrefix of ``pre_``
- GlobalVariableSuffix of ``_post``
Identifies and/or transforms global variable names as follows:
Before:
.. code-block:: c++
int GLOBAL3;
After:
.. code-block:: c++
int pre_global3_post;
.. option:: IgnoreMainLikeFunctions
When set to `true` functions that have a similar signature to ``main`` or
``wmain`` won't enforce checks on the names of their parameters.
Default value is `false`.
.. option:: InlineNamespaceCase
When defined, the check will ensure inline namespaces names conform to the
selected casing.
.. option:: InlineNamespacePrefix
When defined, the check will ensure inline namespaces names will add the
prefixed with the given value (regardless of casing).
.. option:: InlineNamespaceIgnoredRegexp
Identifier naming checks won't be enforced for inline namespaces names
matching this regular expression.
.. option:: InlineNamespaceSuffix
When defined, the check will ensure inline namespaces names will add the
suffix with the given value (regardless of casing).
For example using values of:
- InlineNamespaceCase of ``lower_case``
- InlineNamespacePrefix of ``pre_``
- InlineNamespaceSuffix of ``_post``
Identifies and/or transforms inline namespaces names as follows:
Before:
.. code-block:: c++
namespace FOO_NS {
inline namespace InlineNamespace {
...
}
} // namespace FOO_NS
After:
.. code-block:: c++
namespace FOO_NS {
inline namespace pre_inlinenamespace_post {
...
}
} // namespace FOO_NS
.. option:: LocalConstantCase
When defined, the check will ensure local constant names conform to the
selected casing.
.. option:: LocalConstantPrefix
When defined, the check will ensure local constant names will add the
prefixed with the given value (regardless of casing).
.. option:: LocalConstantIgnoredRegexp
Identifier naming checks won't be enforced for local constant names
matching this regular expression.
.. option:: LocalConstantSuffix
When defined, the check will ensure local constant names will add the
suffix with the given value (regardless of casing).
For example using values of:
- LocalConstantCase of ``lower_case``
- LocalConstantPrefix of ``pre_``
- LocalConstantSuffix of ``_post``
Identifies and/or transforms local constant names as follows:
Before:
.. code-block:: c++
void foo() { int const local_Constant = 3; }
After:
.. code-block:: c++
void foo() { int const pre_local_constant_post = 3; }
.. option:: LocalConstantPointerCase
When defined, the check will ensure local constant pointer names conform to the
selected casing.
.. option:: LocalConstantPointerPrefix
When defined, the check will ensure local constant pointer names will add the
prefixed with the given value (regardless of casing).
.. option:: LocalConstantPointerIgnoredRegexp
Identifier naming checks won't be enforced for local constant pointer names
matching this regular expression.
.. option:: LocalConstantPointerSuffix
When defined, the check will ensure local constant pointer names will add the
suffix with the given value (regardless of casing).
For example using values of:
- LocalConstantPointerCase of ``lower_case``
- LocalConstantPointerPrefix of ``pre_``
- LocalConstantPointerSuffix of ``_post``
Identifies and/or transforms local constant pointer names as follows:
Before:
.. code-block:: c++
void foo() { int const *local_Constant = 3; }
After:
.. code-block:: c++
void foo() { int const *pre_local_constant_post = 3; }
.. option:: LocalPointerCase
When defined, the check will ensure local pointer names conform to the
selected casing.
.. option:: LocalPointerPrefix
When defined, the check will ensure local pointer names will add the
prefixed with the given value (regardless of casing).
.. option:: LocalPointerIgnoredRegexp
Identifier naming checks won't be enforced for local pointer names
matching this regular expression.
.. option:: LocalPointerSuffix
When defined, the check will ensure local pointer names will add the
suffix with the given value (regardless of casing).
For example using values of:
- LocalPointerCase of ``lower_case``
- LocalPointerPrefix of ``pre_``
- LocalPointerSuffix of ``_post``
Identifies and/or transforms local pointer names as follows:
Before:
.. code-block:: c++
void foo() { int *local_Constant; }
After:
.. code-block:: c++
void foo() { int *pre_local_constant_post; }
.. option:: LocalVariableCase
When defined, the check will ensure local variable names conform to the
selected casing.
.. option:: LocalVariablePrefix
When defined, the check will ensure local variable names will add the
prefixed with the given value (regardless of casing).
.. option:: LocalVariableIgnoredRegexp
Identifier naming checks won't be enforced for local variable names
matching this regular expression.
For example using values of:
- LocalVariableCase of ``CamelCase``
- LocalVariableIgnoredRegexp of ``\w{1,2}``
Will exclude variables with a length less than or equal to 2 from the
camel case check applied to other variables.
.. option:: LocalVariableSuffix
When defined, the check will ensure local variable names will add the
suffix with the given value (regardless of casing).
For example using values of:
- LocalVariableCase of ``lower_case``
- LocalVariablePrefix of ``pre_``
- LocalVariableSuffix of ``_post``
Identifies and/or transforms local variable names as follows:
Before:
.. code-block:: c++
void foo() { int local_Constant; }
After:
.. code-block:: c++
void foo() { int pre_local_constant_post; }
.. option:: MacroDefinitionCase
When defined, the check will ensure macro definitions conform to the
selected casing.
.. option:: MacroDefinitionPrefix
When defined, the check will ensure macro definitions will add the
prefixed with the given value (regardless of casing).
.. option:: MacroDefinitionIgnoredRegexp
Identifier naming checks won't be enforced for macro definitions
matching this regular expression.
.. option:: MacroDefinitionSuffix
When defined, the check will ensure macro definitions will add the
suffix with the given value (regardless of casing).
For example using values of:
- MacroDefinitionCase of ``lower_case``
- MacroDefinitionPrefix of ``pre_``
- MacroDefinitionSuffix of ``_post``
Identifies and/or transforms macro definitions as follows:
Before:
.. code-block:: c
#define MY_MacroDefinition
After:
.. code-block:: c
#define pre_my_macro_definition_post
Note: This will not warn on builtin macros or macros defined on the command line
using the ``-D`` flag.
.. option:: MemberCase
When defined, the check will ensure member names conform to the
selected casing.
.. option:: MemberPrefix
When defined, the check will ensure member names will add the
prefixed with the given value (regardless of casing).
.. option:: MemberIgnoredRegexp
Identifier naming checks won't be enforced for member names
matching this regular expression.
.. option:: MemberSuffix
When defined, the check will ensure member names will add the
suffix with the given value (regardless of casing).
For example using values of:
- MemberCase of ``lower_case``
- MemberPrefix of ``pre_``
- MemberSuffix of ``_post``
Identifies and/or transforms member names as follows:
Before:
.. code-block:: c++
class Foo {
char MY_ConstMember_string[4];
}
After:
.. code-block:: c++
class Foo {
char pre_my_constmember_string_post[4];
}
.. option:: MethodCase
When defined, the check will ensure method names conform to the
selected casing.
.. option:: MethodPrefix
When defined, the check will ensure method names will add the
prefixed with the given value (regardless of casing).
.. option:: MethodIgnoredRegexp
Identifier naming checks won't be enforced for method names
matching this regular expression.
.. option:: MethodSuffix
When defined, the check will ensure method names will add the
suffix with the given value (regardless of casing).
For example using values of:
- MethodCase of ``lower_case``
- MethodPrefix of ``pre_``
- MethodSuffix of ``_post``
Identifies and/or transforms method names as follows:
Before:
.. code-block:: c++
class Foo {
char MY_Method_string();
}
After:
.. code-block:: c++
class Foo {
char pre_my_method_string_post();
}
.. option:: NamespaceCase
When defined, the check will ensure namespace names conform to the
selected casing.
.. option:: NamespacePrefix
When defined, the check will ensure namespace names will add the
prefixed with the given value (regardless of casing).
.. option:: NamespaceIgnoredRegexp
Identifier naming checks won't be enforced for namespace names
matching this regular expression.
.. option:: NamespaceSuffix
When defined, the check will ensure namespace names will add the
suffix with the given value (regardless of casing).
For example using values of:
- NamespaceCase of ``lower_case``
- NamespacePrefix of ``pre_``
- NamespaceSuffix of ``_post``
Identifies and/or transforms namespace names as follows:
Before:
.. code-block:: c++
namespace FOO_NS {
...
}
After:
.. code-block:: c++
namespace pre_foo_ns_post {
...
}
.. option:: ParameterCase
When defined, the check will ensure parameter names conform to the
selected casing.
.. option:: ParameterPrefix
When defined, the check will ensure parameter names will add the
prefixed with the given value (regardless of casing).
.. option:: ParameterIgnoredRegexp
Identifier naming checks won't be enforced for parameter names
matching this regular expression.
.. option:: ParameterSuffix
When defined, the check will ensure parameter names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ParameterCase of ``lower_case``
- ParameterPrefix of ``pre_``
- ParameterSuffix of ``_post``
Identifies and/or transforms parameter names as follows:
Before:
.. code-block:: c++
void GLOBAL_FUNCTION(int PARAMETER_1, int const CONST_parameter);
After:
.. code-block:: c++
void GLOBAL_FUNCTION(int pre_parameter_post, int const CONST_parameter);
.. option:: ParameterPackCase
When defined, the check will ensure parameter pack names conform to the
selected casing.
.. option:: ParameterPackPrefix
When defined, the check will ensure parameter pack names will add the
prefixed with the given value (regardless of casing).
.. option:: ParameterPackIgnoredRegexp
Identifier naming checks won't be enforced for parameter pack names
matching this regular expression.
.. option:: ParameterPackSuffix
When defined, the check will ensure parameter pack names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ParameterPackCase of ``lower_case``
- ParameterPackPrefix of ``pre_``
- ParameterPackSuffix of ``_post``
Identifies and/or transforms parameter pack names as follows:
Before:
.. code-block:: c++
template <typename... TYPE_parameters> {
void FUNCTION(int... TYPE_parameters);
}
After:
.. code-block:: c++
template <typename... TYPE_parameters> {
void FUNCTION(int... pre_type_parameters_post);
}
.. option:: PointerParameterCase
When defined, the check will ensure pointer parameter names conform to the
selected casing.
.. option:: PointerParameterPrefix
When defined, the check will ensure pointer parameter names will add the
prefixed with the given value (regardless of casing).
.. option:: PointerParameterIgnoredRegexp
Identifier naming checks won't be enforced for pointer parameter names
matching this regular expression.
.. option:: PointerParameterSuffix
When defined, the check will ensure pointer parameter names will add the
suffix with the given value (regardless of casing).
For example using values of:
- PointerParameterCase of ``lower_case``
- PointerParameterPrefix of ``pre_``
- PointerParameterSuffix of ``_post``
Identifies and/or transforms pointer parameter names as follows:
Before:
.. code-block:: c++
void FUNCTION(int *PARAMETER);
After:
.. code-block:: c++
void FUNCTION(int *pre_parameter_post);
.. option:: PrivateMemberCase
When defined, the check will ensure private member names conform to the
selected casing.
.. option:: PrivateMemberPrefix
When defined, the check will ensure private member names will add the
prefixed with the given value (regardless of casing).
.. option:: PrivateMemberIgnoredRegexp
Identifier naming checks won't be enforced for private member names
matching this regular expression.
.. option:: PrivateMemberSuffix
When defined, the check will ensure private member names will add the
suffix with the given value (regardless of casing).
For example using values of:
- PrivateMemberCase of ``lower_case``
- PrivateMemberPrefix of ``pre_``
- PrivateMemberSuffix of ``_post``
Identifies and/or transforms private member names as follows:
Before:
.. code-block:: c++
class Foo {
private:
int Member_Variable;
}
After:
.. code-block:: c++
class Foo {
private:
int pre_member_variable_post;
}
.. option:: PrivateMethodCase
When defined, the check will ensure private method names conform to the
selected casing.
.. option:: PrivateMethodPrefix
When defined, the check will ensure private method names will add the
prefixed with the given value (regardless of casing).
.. option:: PrivateMethodIgnoredRegexp
Identifier naming checks won't be enforced for private method names
matching this regular expression.
.. option:: PrivateMethodSuffix
When defined, the check will ensure private method names will add the
suffix with the given value (regardless of casing).
For example using values of:
- PrivateMethodCase of ``lower_case``
- PrivateMethodPrefix of ``pre_``
- PrivateMethodSuffix of ``_post``
Identifies and/or transforms private method names as follows:
Before:
.. code-block:: c++
class Foo {
private:
int Member_Method();
}
After:
.. code-block:: c++
class Foo {
private:
int pre_member_method_post();
}
.. option:: ProtectedMemberCase
When defined, the check will ensure protected member names conform to the
selected casing.
.. option:: ProtectedMemberPrefix
When defined, the check will ensure protected member names will add the
prefixed with the given value (regardless of casing).
.. option:: ProtectedMemberIgnoredRegexp
Identifier naming checks won't be enforced for protected member names
matching this regular expression.
.. option:: ProtectedMemberSuffix
When defined, the check will ensure protected member names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ProtectedMemberCase of ``lower_case``
- ProtectedMemberPrefix of ``pre_``
- ProtectedMemberSuffix of ``_post``
Identifies and/or transforms protected member names as follows:
Before:
.. code-block:: c++
class Foo {
protected:
int Member_Variable;
}
After:
.. code-block:: c++
class Foo {
protected:
int pre_member_variable_post;
}
.. option:: ProtectedMethodCase
When defined, the check will ensure protected method names conform to the
selected casing.
.. option:: ProtectedMethodPrefix
When defined, the check will ensure protected method names will add the
prefixed with the given value (regardless of casing).
.. option:: ProtectedMethodIgnoredRegexp
Identifier naming checks won't be enforced for protected method names
matching this regular expression.
.. option:: ProtectedMethodSuffix
When defined, the check will ensure protected method names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ProtectedMethodCase of ``lower_case``
- ProtectedMethodPrefix of ``pre_``
- ProtectedMethodSuffix of ``_post``
Identifies and/or transforms protect method names as follows:
Before:
.. code-block:: c++
class Foo {
protected:
int Member_Method();
}
After:
.. code-block:: c++
class Foo {
protected:
int pre_member_method_post();
}
.. option:: PublicMemberCase
When defined, the check will ensure public member names conform to the
selected casing.
.. option:: PublicMemberPrefix
When defined, the check will ensure public member names will add the
prefixed with the given value (regardless of casing).
.. option:: PublicMemberIgnoredRegexp
Identifier naming checks won't be enforced for public member names
matching this regular expression.
.. option:: PublicMemberSuffix
When defined, the check will ensure public member names will add the
suffix with the given value (regardless of casing).
For example using values of:
- PublicMemberCase of ``lower_case``
- PublicMemberPrefix of ``pre_``
- PublicMemberSuffix of ``_post``
Identifies and/or transforms public member names as follows:
Before:
.. code-block:: c++
class Foo {
public:
int Member_Variable;
}
After:
.. code-block:: c++
class Foo {
public:
int pre_member_variable_post;
}
.. option:: PublicMethodCase
When defined, the check will ensure public method names conform to the
selected casing.
.. option:: PublicMethodPrefix
When defined, the check will ensure public method names will add the
prefixed with the given value (regardless of casing).
.. option:: PublicMethodIgnoredRegexp
Identifier naming checks won't be enforced for public method names
matching this regular expression.
.. option:: PublicMethodSuffix
When defined, the check will ensure public method names will add the
suffix with the given value (regardless of casing).
For example using values of:
- PublicMethodCase of ``lower_case``
- PublicMethodPrefix of ``pre_``
- PublicMethodSuffix of ``_post``
Identifies and/or transforms public method names as follows:
Before:
.. code-block:: c++
class Foo {
public:
int Member_Method();
}
After:
.. code-block:: c++
class Foo {
public:
int pre_member_method_post();
}
.. option:: ScopedEnumConstantCase
When defined, the check will ensure scoped enum constant names conform to
the selected casing.
.. option:: ScopedEnumConstantPrefix
When defined, the check will ensure scoped enum constant names will add the
prefixed with the given value (regardless of casing).
.. option:: ScopedEnumConstantIgnoredRegexp
Identifier naming checks won't be enforced for scoped enum constant names
matching this regular expression.
.. option:: ScopedEnumConstantSuffix
When defined, the check will ensure scoped enum constant names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ScopedEnumConstantCase of ``lower_case``
- ScopedEnumConstantPrefix of ``pre_``
- ScopedEnumConstantSuffix of ``_post``
Identifies and/or transforms enumeration constant names as follows:
Before:
.. code-block:: c++
enum class FOO { One, Two, Three };
After:
.. code-block:: c++
enum class FOO { pre_One_post, pre_Two_post, pre_Three_post };
.. option:: StaticConstantCase
When defined, the check will ensure static constant names conform to the
selected casing.
.. option:: StaticConstantPrefix
When defined, the check will ensure static constant names will add the
prefixed with the given value (regardless of casing).
.. option:: StaticConstantIgnoredRegexp
Identifier naming checks won't be enforced for static constant names
matching this regular expression.
.. option:: StaticConstantSuffix
When defined, the check will ensure static constant names will add the
suffix with the given value (regardless of casing).
For example using values of:
- StaticConstantCase of ``lower_case``
- StaticConstantPrefix of ``pre_``
- StaticConstantSuffix of ``_post``
Identifies and/or transforms static constant names as follows:
Before:
.. code-block:: c++
static unsigned const MyConstStatic_array[] = {1, 2, 3};
After:
.. code-block:: c++
static unsigned const pre_myconststatic_array_post[] = {1, 2, 3};
.. option:: StaticVariableCase
When defined, the check will ensure static variable names conform to the
selected casing.
.. option:: StaticVariablePrefix
When defined, the check will ensure static variable names will add the
prefixed with the given value (regardless of casing).
.. option:: StaticVariableIgnoredRegexp
Identifier naming checks won't be enforced for static variable names
matching this regular expression.
.. option:: StaticVariableSuffix
When defined, the check will ensure static variable names will add the
suffix with the given value (regardless of casing).
For example using values of:
- StaticVariableCase of ``lower_case``
- StaticVariablePrefix of ``pre_``
- StaticVariableSuffix of ``_post``
Identifies and/or transforms static variable names as follows:
Before:
.. code-block:: c++
static unsigned MyStatic_array[] = {1, 2, 3};
After:
.. code-block:: c++
static unsigned pre_mystatic_array_post[] = {1, 2, 3};
.. option:: StructCase
When defined, the check will ensure struct names conform to the
selected casing.
.. option:: StructPrefix
When defined, the check will ensure struct names will add the
prefixed with the given value (regardless of casing).
.. option:: StructIgnoredRegexp
Identifier naming checks won't be enforced for struct names
matching this regular expression.
.. option:: StructSuffix
When defined, the check will ensure struct names will add the
suffix with the given value (regardless of casing).
For example using values of:
- StructCase of ``lower_case``
- StructPrefix of ``pre_``
- StructSuffix of ``_post``
Identifies and/or transforms struct names as follows:
Before:
.. code-block:: c++
struct FOO {
FOO();
~FOO();
};
After:
.. code-block:: c++
struct pre_foo_post {
pre_foo_post();
~pre_foo_post();
};
.. option:: TemplateParameterCase
When defined, the check will ensure template parameter names conform to the
selected casing.
.. option:: TemplateParameterPrefix
When defined, the check will ensure template parameter names will add the
prefixed with the given value (regardless of casing).
.. option:: TemplateParameterIgnoredRegexp
Identifier naming checks won't be enforced for template parameter names
matching this regular expression.
.. option:: TemplateParameterSuffix
When defined, the check will ensure template parameter names will add the
suffix with the given value (regardless of casing).
For example using values of:
- TemplateParameterCase of ``lower_case``
- TemplateParameterPrefix of ``pre_``
- TemplateParameterSuffix of ``_post``
Identifies and/or transforms template parameter names as follows:
Before:
.. code-block:: c++
template <typename T> class Foo {};
After:
.. code-block:: c++
template <typename pre_t_post> class Foo {};
.. option:: TemplateTemplateParameterCase
When defined, the check will ensure template template parameter names conform to the
selected casing.
.. option:: TemplateTemplateParameterPrefix
When defined, the check will ensure template template parameter names will add the
prefixed with the given value (regardless of casing).
.. option:: TemplateTemplateParameterIgnoredRegexp
Identifier naming checks won't be enforced for template template parameter
names matching this regular expression.
.. option:: TemplateTemplateParameterSuffix
When defined, the check will ensure template template parameter names will add the
suffix with the given value (regardless of casing).
For example using values of:
- TemplateTemplateParameterCase of ``lower_case``
- TemplateTemplateParameterPrefix of ``pre_``
- TemplateTemplateParameterSuffix of ``_post``
Identifies and/or transforms template template parameter names as follows:
Before:
.. code-block:: c++
template <template <typename> class TPL_parameter, int COUNT_params,
typename... TYPE_parameters>
After:
.. code-block:: c++
template <template <typename> class pre_tpl_parameter_post, int COUNT_params,
typename... TYPE_parameters>
.. option:: TypeAliasCase
When defined, the check will ensure type alias names conform to the
selected casing.
.. option:: TypeAliasPrefix
When defined, the check will ensure type alias names will add the
prefixed with the given value (regardless of casing).
.. option:: TypeAliasIgnoredRegexp
Identifier naming checks won't be enforced for type alias names
matching this regular expression.
.. option:: TypeAliasSuffix
When defined, the check will ensure type alias names will add the
suffix with the given value (regardless of casing).
For example using values of:
- TypeAliasCase of ``lower_case``
- TypeAliasPrefix of ``pre_``
- TypeAliasSuffix of ``_post``
Identifies and/or transforms type alias names as follows:
Before:
.. code-block:: c++
using MY_STRUCT_TYPE = my_structure;
After:
.. code-block:: c++
using pre_my_struct_type_post = my_structure;
.. option:: TypedefCase
When defined, the check will ensure typedef names conform to the
selected casing.
.. option:: TypedefPrefix
When defined, the check will ensure typedef names will add the
prefixed with the given value (regardless of casing).
.. option:: TypedefIgnoredRegexp
Identifier naming checks won't be enforced for typedef names
matching this regular expression.
.. option:: TypedefSuffix
When defined, the check will ensure typedef names will add the
suffix with the given value (regardless of casing).
For example using values of:
- TypedefCase of ``lower_case``
- TypedefPrefix of ``pre_``
- TypedefSuffix of ``_post``
Identifies and/or transforms typedef names as follows:
Before:
.. code-block:: c++
typedef int MYINT;
After:
.. code-block:: c++
typedef int pre_myint_post;
.. option:: TypeTemplateParameterCase
When defined, the check will ensure type template parameter names conform to the
selected casing.
.. option:: TypeTemplateParameterPrefix
When defined, the check will ensure type template parameter names will add the
prefixed with the given value (regardless of casing).
.. option:: TypeTemplateParameterIgnoredRegexp
Identifier naming checks won't be enforced for type template names
matching this regular expression.
.. option:: TypeTemplateParameterSuffix
When defined, the check will ensure type template parameter names will add the
suffix with the given value (regardless of casing).
For example using values of:
- TypeTemplateParameterCase of ``lower_case``
- TypeTemplateParameterPrefix of ``pre_``
- TypeTemplateParameterSuffix of ``_post``
Identifies and/or transforms type template parameter names as follows:
Before:
.. code-block:: c++
template <template <typename> class TPL_parameter, int COUNT_params,
typename... TYPE_parameters>
After:
.. code-block:: c++
template <template <typename> class TPL_parameter, int COUNT_params,
typename... pre_type_parameters_post>
.. option:: UnionCase
When defined, the check will ensure union names conform to the
selected casing.
.. option:: UnionPrefix
When defined, the check will ensure union names will add the
prefixed with the given value (regardless of casing).
.. option:: UnionIgnoredRegexp
Identifier naming checks won't be enforced for union names
matching this regular expression.
.. option:: UnionSuffix
When defined, the check will ensure union names will add the
suffix with the given value (regardless of casing).
For example using values of:
- UnionCase of ``lower_case``
- UnionPrefix of ``pre_``
- UnionSuffix of ``_post``
Identifies and/or transforms union names as follows:
Before:
.. code-block:: c++
union FOO {
int a;
char b;
};
After:
.. code-block:: c++
union pre_foo_post {
int a;
char b;
};
.. option:: ValueTemplateParameterCase
When defined, the check will ensure value template parameter names conform to the
selected casing.
.. option:: ValueTemplateParameterPrefix
When defined, the check will ensure value template parameter names will add the
prefixed with the given value (regardless of casing).
.. option:: ValueTemplateParameterIgnoredRegexp
Identifier naming checks won't be enforced for value template parameter
names matching this regular expression.
.. option:: ValueTemplateParameterSuffix
When defined, the check will ensure value template parameter names will add the
suffix with the given value (regardless of casing).
For example using values of:
- ValueTemplateParameterCase of ``lower_case``
- ValueTemplateParameterPrefix of ``pre_``
- ValueTemplateParameterSuffix of ``_post``
Identifies and/or transforms value template parameter names as follows:
Before:
.. code-block:: c++
template <template <typename> class TPL_parameter, int COUNT_params,
typename... TYPE_parameters>
After:
.. code-block:: c++
template <template <typename> class TPL_parameter, int pre_count_params_post,
typename... TYPE_parameters>
.. option:: VariableCase
When defined, the check will ensure variable names conform to the
selected casing.
.. option:: VariablePrefix
When defined, the check will ensure variable names will add the
prefixed with the given value (regardless of casing).
.. option:: VariableIgnoredRegexp
Identifier naming checks won't be enforced for variable names
matching this regular expression.
.. option:: VariableSuffix
When defined, the check will ensure variable names will add the
suffix with the given value (regardless of casing).
For example using values of:
- VariableCase of ``lower_case``
- VariablePrefix of ``pre_``
- VariableSuffix of ``_post``
Identifies and/or transforms variable names as follows:
Before:
.. code-block:: c++
unsigned MyVariable;
After:
.. code-block:: c++
unsigned pre_myvariable_post;
.. option:: VirtualMethodCase
When defined, the check will ensure virtual method names conform to the
selected casing.
.. option:: VirtualMethodPrefix
When defined, the check will ensure virtual method names will add the
prefixed with the given value (regardless of casing).
.. option:: VirtualMethodIgnoredRegexp
Identifier naming checks won't be enforced for virtual method names
matching this regular expression.
.. option:: VirtualMethodSuffix
When defined, the check will ensure virtual method names will add the
suffix with the given value (regardless of casing).
For example using values of:
- VirtualMethodCase of ``lower_case``
- VirtualMethodPrefix of ``pre_``
- VirtualMethodSuffix of ``_post``
Identifies and/or transforms virtual method names as follows:
Before:
.. code-block:: c++
class Foo {
public:
virtual int MemberFunction();
}
After:
.. code-block:: c++
class Foo {
public:
virtual int pre_member_function_post();
}
:orphan:
.. title:: clang-tidy - readability-implicit-bool-cast
.. meta::
:http-equiv=refresh: 5;URL=readability-implicit-bool-conversion.html
readability-implicit-bool-cast
==============================
This check has been renamed to `readability-implicit-bool-conversion
<readability-implicit-bool-conversion.html>`_.
.. title:: clang-tidy - readability-implicit-bool-conversion
readability-implicit-bool-conversion
====================================
This check can be used to find implicit conversions between built-in types and
booleans. Depending on use case, it may simply help with readability of the code,
or in some cases, point to potential bugs which remain unnoticed due to implicit
conversions.
The following is a real-world example of bug which was hiding behind implicit
``bool`` conversion:
.. code-block:: c++
class Foo {
int m_foo;
public:
void setFoo(bool foo) { m_foo = foo; } // warning: implicit conversion bool -> int
int getFoo() { return m_foo; }
};
void use(Foo& foo) {
bool value = foo.getFoo(); // warning: implicit conversion int -> bool
}
This code is the result of unsuccessful refactoring, where type of ``m_foo``
changed from ``bool`` to ``int``. The programmer forgot to change all
occurrences of ``bool``, and the remaining code is no longer correct, yet it
still compiles without any visible warnings.
In addition to issuing warnings, fix-it hints are provided to help solve the
reported issues. This can be used for improving readability of code, for
example:
.. code-block:: c++
void conversionsToBool() {
float floating;
bool boolean = floating;
// ^ propose replacement: bool boolean = floating != 0.0f;
int integer;
if (integer) {}
// ^ propose replacement: if (integer != 0) {}
int* pointer;
if (!pointer) {}
// ^ propose replacement: if (pointer == nullptr) {}
while (1) {}
// ^ propose replacement: while (true) {}
}
void functionTakingInt(int param);
void conversionsFromBool() {
bool boolean;
functionTakingInt(boolean);
// ^ propose replacement: functionTakingInt(static_cast<int>(boolean));
functionTakingInt(true);
// ^ propose replacement: functionTakingInt(1);
}
In general, the following conversion types are checked:
- integer expression/literal to boolean (conversion from a single bit bitfield
to boolean is explicitly allowed, since there's no ambiguity / information
loss in this case),
- floating expression/literal to boolean,
- pointer/pointer to member/``nullptr``/``NULL`` to boolean,
- boolean expression/literal to integer (conversion from boolean to a single
bit bitfield is explicitly allowed),
- boolean expression/literal to floating.
The rules for generating fix-it hints are:
- in case of conversions from other built-in type to bool, an explicit
comparison is proposed to make it clear what exactly is being compared:
- ``bool boolean = floating;`` is changed to
``bool boolean = floating == 0.0f;``,
- for other types, appropriate literals are used (``0``, ``0u``, ``0.0f``,
``0.0``, ``nullptr``),
- in case of negated expressions conversion to bool, the proposed replacement
with comparison is simplified:
- ``if (!pointer)`` is changed to ``if (pointer == nullptr)``,
- in case of conversions from bool to other built-in types, an explicit
``static_cast`` is proposed to make it clear that a conversion is taking
place:
- ``int integer = boolean;`` is changed to
``int integer = static_cast<int>(boolean);``,
- if the conversion is performed on type literals, an equivalent literal is
proposed, according to what type is actually expected, for example:
- ``functionTakingBool(0);`` is changed to ``functionTakingBool(false);``,
- ``functionTakingInt(true);`` is changed to ``functionTakingInt(1);``,
- for other types, appropriate literals are used (``false``, ``true``, ``0``,
``1``, ``0u``, ``1u``, ``0.0f``, ``1.0f``, ``0.0``, ``1.0f``).
Some additional accommodations are made for pre-C++11 dialects:
- ``false`` literal conversion to pointer is detected,
- instead of ``nullptr`` literal, ``0`` is proposed as replacement.
Occurrences of implicit conversions inside macros and template instantiations
are deliberately ignored, as it is not clear how to deal with such cases.
Options
-------
.. option:: AllowIntegerConditions
When `true`, the check will allow conditional integer conversions. Default
is `false`.
.. option:: AllowPointerConditions
When `true`, the check will allow conditional pointer conversions. Default
is `false`.
.. title:: clang-tidy - readability-inconsistent-declaration-parameter-name
readability-inconsistent-declaration-parameter-name
===================================================
Find function declarations which differ in parameter names.
Example:
.. code-block:: c++
// in foo.hpp:
void foo(int a, int b, int c);
// in foo.cpp:
void foo(int d, int e, int f); // warning
This check should help to enforce consistency in large projects, where it often
happens that a definition of function is refactored, changing the parameter
names, but its declaration in header file is not updated. With this check, we
can easily find and correct such inconsistencies, keeping declaration and
definition always in sync.
Unnamed parameters are allowed and are not taken into account when comparing
function declarations, for example:
.. code-block:: c++
void foo(int a);
void foo(int); // no warning
One name is also allowed to be a case-insensitive prefix/suffix of the other:
.. code-block:: c++
void foo(int count);
void foo(int count_input) { // no warning
int count = adjustCount(count_input);
}
To help with refactoring, in some cases fix-it hints are generated to align
parameter names to a single naming convention. This works with the assumption
that the function definition is the most up-to-date version, as it directly
references parameter names in its body. Example:
.. code-block:: c++
void foo(int a); // warning and fix-it hint (replace "a" to "b")
int foo(int b) { return b + 2; } // definition with use of "b"
In the case of multiple redeclarations or function template specializations,
a warning is issued for every redeclaration or specialization inconsistent with
the definition or the first declaration seen in a translation unit.
.. option:: IgnoreMacros
If this option is set to `true` (default is `true`), the check will not warn
about names declared inside macros.
.. option:: Strict
If this option is set to `true` (default is `false`), then names must match
exactly (or be absent).
.. title:: clang-tidy - readability-isolate-declaration
readability-isolate-declaration
===============================
Detects local variable declarations declaring more than one variable and
tries to refactor the code to one statement per declaration.
The automatic code-transformation will use the same indentation as the original
for every created statement and add a line break after each statement.
It keeps the order of the variable declarations consistent, too.
.. code-block:: c++
void f() {
int * pointer = nullptr, value = 42, * const const_ptr = &value;
// This declaration will be diagnosed and transformed into:
// int * pointer = nullptr;
// int value = 42;
// int * const const_ptr = &value;
}
The check excludes places where it is necessary or common to declare
multiple variables in one statement and there is no other way supported in the
language. Please note that structured bindings are not considered.
.. code-block:: c++
// It is not possible to transform this declaration and doing the declaration
// before the loop will increase the scope of the variable 'Begin' and 'End'
// which is undesirable.
for (int Begin = 0, End = 100; Begin < End; ++Begin);
if (int Begin = 42, Result = some_function(Begin); Begin == Result);
// It is not possible to transform this declaration because the result is
// not functionality preserving as 'j' and 'k' would not be part of the
// 'if' statement anymore.
if (SomeCondition())
int i = 42, j = 43, k = function(i,j);
Limitations
-----------
Global variables and member variables are excluded.
The check currently does not support the automatic transformation of
member-pointer-types.
.. code-block:: c++
struct S {
int a;
const int b;
void f() {}
};
void f() {
// Only a diagnostic message is emitted
int S::*p = &S::a, S::*const q = &S::a;
}
Furthermore, the transformation is very cautious when it detects various kinds
of macros or preprocessor directives in the range of the statement. In this
case the transformation will not happen to avoid unexpected side-effects due to
macros.
.. code-block:: c++
#define NULL 0
#define MY_NICE_TYPE int **
#define VAR_NAME(name) name##__LINE__
#define A_BUNCH_OF_VARIABLES int m1 = 42, m2 = 43, m3 = 44;
void macros() {
int *p1 = NULL, *p2 = NULL;
// Will be transformed to
// int *p1 = NULL;
// int *p2 = NULL;
MY_NICE_TYPE p3, v1, v2;
// Won't be transformed, but a diagnostic is emitted.
int VAR_NAME(v3),
VAR_NAME(v4),
VAR_NAME(v5);
// Won't be transformed, but a diagnostic is emitted.
A_BUNCH_OF_VARIABLES
// Won't be transformed, but a diagnostic is emitted.
int Unconditional,
#if CONFIGURATION
IfConfigured = 42,
#else
IfConfigured = 0;
#endif
// Won't be transformed, but a diagnostic is emitted.
}
.. title:: clang-tidy - readability-magic-numbers
readability-magic-numbers
=========================
Detects magic numbers, integer or floating point literals that are embedded in
code and not introduced via constants or symbols.
Many coding guidelines advise replacing the magic values with symbolic
constants to improve readability. Here are a few references:
* `Rule ES.45: Avoid “magic constants”; use symbolic constants in C++ Core Guidelines <https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-magic>`_
* `Rule 5.1.1 Use symbolic names instead of literal values in code in High Integrity C++ <http://www.codingstandard.com/rule/5-1-1-use-symbolic-names-instead-of-literal-values-in-code/>`_
* Item 17 in "C++ Coding Standards: 101 Rules, Guidelines and Best
Practices" by Herb Sutter and Andrei Alexandrescu
* Chapter 17 in "Clean Code - A handbook of agile software craftsmanship."
by Robert C. Martin
* Rule 20701 in "TRAIN REAL TIME DATA PROTOCOL Coding Rules" by Armin-Hagen
Weiss, Bombardier
* http://wiki.c2.com/?MagicNumber
Examples of magic values:
.. code-block:: c++
double circleArea = 3.1415926535 * radius * radius;
double totalCharge = 1.08 * itemPrice;
int getAnswer() {
return -3; // FILENOTFOUND
}
for (int mm = 1; mm <= 12; ++mm) {
std::cout << month[mm] << '\n';
}
Example with magic values refactored:
.. code-block:: c++
double circleArea = M_PI * radius * radius;
const double TAX_RATE = 0.08; // or make it variable and read from a file
double totalCharge = (1.0 + TAX_RATE) * itemPrice;
int getAnswer() {
return E_FILE_NOT_FOUND;
}
for (int mm = 1; mm <= MONTHS_IN_A_YEAR; ++mm) {
std::cout << month[mm] << '\n';
}
For integral literals by default only `0` and `1` (and `-1`) integer values
are accepted without a warning. This can be overridden with the
:option:`IgnoredIntegerValues` option. Negative values are accepted if their
absolute value is present in the :option:`IgnoredIntegerValues` list.
As a special case for integral values, all powers of two can be accepted
without warning by enabling the :option:`IgnorePowersOf2IntegerValues` option.
For floating point literals by default the `0.0` floating point value is
accepted without a warning. The set of ignored floating point literals can
be configured using the :option:`IgnoredFloatingPointValues` option.
For each value in that set, the given string value is converted to a
floating-point value representation used by the target architecture. If a
floating-point literal value compares equal to one of the converted values,
then that literal is not diagnosed by this check. Because floating-point
equality is used to determine whether to diagnose or not, the user needs to
be aware of the details of floating-point representations for any values that
cannot be precisely represented for their target architecture.
For each value in the :option:`IgnoredFloatingPointValues` set, both the
single-precision form and double-precision form are accepted (for example, if
3.14 is in the set, neither 3.14f nor 3.14 will produce a warning).
Scientific notation is supported for both source code input and option.
Alternatively, the check for the floating point numbers can be disabled for
all floating point values by enabling the
:option:`IgnoreAllFloatingPointValues` option.
Since values `0` and `0.0` are so common as the base counter of loops,
or initialization values for sums, they are always accepted without warning,
even if not present in the respective ignored values list.
Options
-------
.. option:: IgnoredIntegerValues
Semicolon-separated list of magic positive integers that will be accepted
without a warning. Default values are `{1, 2, 3, 4}`, and `0` is accepted
unconditionally.
.. option:: IgnorePowersOf2IntegerValues
Boolean value indicating whether to accept all powers-of-two integer values
without warning. Default value is `false`.
.. option:: IgnoredFloatingPointValues
Semicolon-separated list of magic positive floating point values that will
be accepted without a warning. Default values are `{1.0, 100.0}` and `0.0`
is accepted unconditionally.
.. option:: IgnoreAllFloatingPointValues
Boolean value indicating whether to accept all floating point values without
warning. Default value is `false`.
.. option:: IgnoreBitFieldsWidths
Boolean value indicating whether to accept magic numbers as bit field widths
without warning. This is useful for example for register definitions which
are generated from hardware specifications. Default value is `true`.
.. title:: clang-tidy - readability-make-member-function-const
readability-make-member-function-const
======================================
Finds non-static member functions that can be made ``const``
because the functions don't use ``this`` in a non-const way.
This check tries to annotate methods according to
`logical constness <https://isocpp.org/wiki/faq/const-correctness#logical-vs-physical-state>`_
(not physical constness).
Therefore, it will suggest to add a ``const`` qualifier to a non-const
method only if this method does something that is already possible though the
public interface on a ``const`` pointer to the object:
* reading a public member variable
* calling a public const-qualified member function
* returning const-qualified ``this``
* passing const-qualified ``this`` as a parameter.
This check will also suggest to add a ``const`` qualifier to a non-const
method if this method uses private data and functions in a limited number of
ways where logical constness and physical constness coincide:
* reading a member variable of builtin type
Specifically, this check will not suggest to add a ``const`` to a non-const
method if the method reads a private member variable of pointer type because
that allows to modify the pointee which might not preserve logical constness.
For the same reason, it does not allow to call private member functions
or member functions on private member variables.
In addition, this check ignores functions that
* are declared ``virtual``
* contain a ``const_cast``
* are templated or part of a class template
* have an empty body
* do not (implicitly) use ``this`` at all
(see `readability-convert-member-functions-to-static <readability-convert-member-functions-to-static.html>`_).
The following real-world examples will be preserved by the check:
.. code-block:: c++
class E1 {
Pimpl &getPimpl() const;
public:
int &get() {
// Calling a private member function disables this check.
return getPimpl()->i;
}
...
};
class E2 {
public:
const int *get() const;
// const_cast disables this check.
S *get() {
return const_cast<int*>(const_cast<const C*>(this)->get());
}
...
};
After applying modifications as suggested by the check, running the check again
might find more opportunities to mark member functions ``const``.
.. title:: clang-tidy - readability-misleading-indentation
readability-misleading-indentation
==================================
Correct indentation helps to understand code. Mismatch of the syntactical
structure and the indentation of the code may hide serious problems.
Missing braces can also make it significantly harder to read the code,
therefore it is important to use braces.
The way to avoid dangling else is to always check that an ``else`` belongs
to the ``if`` that begins in the same column.
You can omit braces when your inner part of e.g. an ``if`` statement has only
one statement in it. Although in that case you should begin the next statement
in the same column with the ``if``.
Examples:
.. code-block:: c++
// Dangling else:
if (cond1)
if (cond2)
foo1();
else
foo2(); // Wrong indentation: else belongs to if(cond2) statement.
// Missing braces:
if (cond1)
foo1();
foo2(); // Not guarded by if(cond1).
Limitations
-----------
Note that this check only works as expected when the tabs or spaces are used
consistently and not mixed.
.. title:: clang-tidy - readability-misplaced-array-index
readability-misplaced-array-index
=================================
This check warns for unusual array index syntax.
The following code has unusual array index syntax:
.. code-block:: c++
void f(int *X, int Y) {
Y[X] = 0;
}
becomes
.. code-block:: c++
void f(int *X, int Y) {
X[Y] = 0;
}
The check warns about such unusual syntax for readability reasons:
* There are programmers that are not familiar with this unusual syntax.
* It is possible that variables are mixed up.
.. title:: clang-tidy - readability-named-parameter
readability-named-parameter
===========================
Find functions with unnamed arguments.
The check implements the following rule originating in the Google C++ Style
Guide:
https://google.github.io/styleguide/cppguide.html#Function_Declarations_and_Definitions
All parameters should be named, with identical names in the declaration and
implementation.
Corresponding cpplint.py check name: `readability/function`.
.. title:: clang-tidy - readability-non-const-parameter
readability-non-const-parameter
===============================
The check finds function parameters of a pointer type that could be changed to
point to a constant type instead.
When ``const`` is used properly, many mistakes can be avoided. Advantages when
using ``const`` properly:
- prevent unintentional modification of data;
- get additional warnings such as using uninitialized data;
- make it easier for developers to see possible side effects.
This check is not strict about constness, it only warns when the constness will
make the function interface safer.
.. code-block:: c++
// warning here; the declaration "const char *p" would make the function
// interface safer.
char f1(char *p) {
return *p;
}
// no warning; the declaration could be more const "const int * const p" but
// that does not make the function interface safer.
int f2(const int *p) {
return *p;
}
// no warning; making x const does not make the function interface safer
int f3(int x) {
return x;
}
// no warning; Technically, *p can be const ("const struct S *p"). But making
// *p const could be misleading. People might think that it's safe to pass
// const data to this function.
struct S { int *a; int *b; };
int f3(struct S *p) {
*(p->a) = 0;
}
.. title:: clang-tidy - readability-qualified-auto
readability-qualified-auto
==========================
Adds pointer qualifications to ``auto``-typed variables that are deduced to
pointers.
`LLVM Coding Standards <https://llvm.org/docs/CodingStandards.html#beware-unnecessary-copies-with-auto>`_
advises to make it obvious if a ``auto`` typed variable is a pointer. This
check will transform ``auto`` to ``auto *`` when the type is deduced to be a
pointer.
.. code-block:: c++
for (auto Data : MutatablePtrContainer) {
change(*Data);
}
for (auto Data : ConstantPtrContainer) {
observe(*Data);
}
Would be transformed into:
.. code-block:: c++
for (auto *Data : MutatablePtrContainer) {
change(*Data);
}
for (const auto *Data : ConstantPtrContainer) {
observe(*Data);
}
Note ``const`` ``volatile`` qualified types will retain their ``const`` and
``volatile`` qualifiers. Pointers to pointers will not be fully qualified.
.. code-block:: c++
const auto Foo = cast<int *>(Baz1);
const auto Bar = cast<const int *>(Baz2);
volatile auto FooBar = cast<int *>(Baz3);
auto BarFoo = cast<int **>(Baz4);
Would be transformed into:
.. code-block:: c++
auto *const Foo = cast<int *>(Baz1);
const auto *const Bar = cast<const int *>(Baz2);
auto *volatile FooBar = cast<int *>(Baz3);
auto *BarFoo = cast<int **>(Baz4);
Options
-------
.. option:: AddConstToQualified
When set to `true` the check will add const qualifiers variables defined as
``auto *`` or ``auto &`` when applicable.
Default value is `true`.
.. code-block:: c++
auto Foo1 = cast<const int *>(Bar1);
auto *Foo2 = cast<const int *>(Bar2);
auto &Foo3 = cast<const int &>(Bar3);
If AddConstToQualified is set to `false`, it will be transformed into:
.. code-block:: c++
const auto *Foo1 = cast<const int *>(Bar1);
auto *Foo2 = cast<const int *>(Bar2);
auto &Foo3 = cast<const int &>(Bar3);
Otherwise it will be transformed into:
.. code-block:: c++
const auto *Foo1 = cast<const int *>(Bar1);
const auto *Foo2 = cast<const int *>(Bar2);
const auto &Foo3 = cast<const int &>(Bar3);
Note in the LLVM alias, the default value is `false`.
.. title:: clang-tidy - readability-redundant-access-specifiers
readability-redundant-access-specifiers
=======================================
Finds classes, structs, and unions containing redundant member (field and
method) access specifiers.
Example
-------
.. code-block:: c++
class Foo {
public:
int x;
int y;
public:
int z;
protected:
int a;
public:
int c;
}
In the example above, the second ``public`` declaration can be removed without
any changes of behavior.
Options
-------
.. option:: CheckFirstDeclaration
If set to `true`, the check will also diagnose if the first access
specifier declaration is redundant (e.g. ``private`` inside ``class``,
or ``public`` inside ``struct`` or ``union``).
Default is `false`.
Example
^^^^^^^
.. code-block:: c++
struct Bar {
public:
int x;
}
If `CheckFirstDeclaration` option is enabled, a warning about redundant
access specifier will be emitted, because ``public`` is the default member access
for structs.
.. title:: clang-tidy - readability-redundant-control-flow
readability-redundant-control-flow
==================================
This check looks for procedures (functions returning no value) with ``return``
statements at the end of the function. Such ``return`` statements are redundant.
Loop statements (``for``, ``while``, ``do while``) are checked for redundant
``continue`` statements at the end of the loop body.
Examples:
The following function `f` contains a redundant ``return`` statement:
.. code-block:: c++
extern void g();
void f() {
g();
return;
}
becomes
.. code-block:: c++
extern void g();
void f() {
g();
}
The following function `k` contains a redundant ``continue`` statement:
.. code-block:: c++
void k() {
for (int i = 0; i < 10; ++i) {
continue;
}
}
becomes
.. code-block:: c++
void k() {
for (int i = 0; i < 10; ++i) {
}
}
.. title:: clang-tidy - readability-redundant-declaration
readability-redundant-declaration
=================================
Finds redundant variable and function declarations.
.. code-block:: c++
extern int X;
extern int X;
becomes
.. code-block:: c++
extern int X;
Such redundant declarations can be removed without changing program behaviour.
They can for instance be unintentional left overs from previous refactorings
when code has been moved around. Having redundant declarations could in worst
case mean that there are typos in the code that cause bugs.
Normally the code can be automatically fixed, :program:`clang-tidy` can remove
the second declaration. However there are 2 cases when you need to fix the code
manually:
* When the declarations are in different header files;
* When multiple variables are declared together.
Options
-------
.. option:: IgnoreMacros
If set to `true`, the check will not give warnings inside macros. Default
is `true`.
.. title:: clang-tidy - readability-redundant-function-ptr-dereference
readability-redundant-function-ptr-dereference
==============================================
Finds redundant dereferences of a function pointer.
Before:
.. code-block:: c++
int f(int,int);
int (*p)(int, int) = &f;
int i = (**p)(10, 50);
After:
.. code-block:: c++
int f(int,int);
int (*p)(int, int) = &f;
int i = (*p)(10, 50);
.. title:: clang-tidy - readability-redundant-member-init
readability-redundant-member-init
=================================
Finds member initializations that are unnecessary because the same default
constructor would be called if they were not present.
Example
-------
.. code-block:: c++
// Explicitly initializing the member s is unnecessary.
class Foo {
public:
Foo() : s() {}
private:
std::string s;
};
Options
-------
.. option:: IgnoreBaseInCopyConstructors
Default is `false`.
When `true`, the check will ignore unnecessary base class initializations
within copy constructors, since some compilers issue warnings/errors when
base classes are not explicitly intialized in copy constructors. For example,
``gcc`` with ``-Wextra`` or ``-Werror=extra`` issues warning or error
``base class 'Bar' should be explicitly initialized in the copy constructor``
if ``Bar()`` were removed in the following example:
.. code-block:: c++
// Explicitly initializing member s and base class Bar is unnecessary.
struct Foo : public Bar {
// Remove s() below. If IgnoreBaseInCopyConstructors!=0, keep Bar().
Foo(const Foo& foo) : Bar(), s() {}
std::string s;
};
.. title:: clang-tidy - readability-redundant-preprocessor
readability-redundant-preprocessor
==================================
Finds potentially redundant preprocessor directives. At the moment the
following cases are detected:
* `#ifdef` .. `#endif` pairs which are nested inside an outer pair with the
same condition. For example:
.. code-block:: c++
#ifdef FOO
#ifdef FOO // inner ifdef is considered redundant
void f();
#endif
#endif
* Same for `#ifndef` .. `#endif` pairs. For example:
.. code-block:: c++
#ifndef FOO
#ifndef FOO // inner ifndef is considered redundant
void f();
#endif
#endif
* `#ifndef` inside an `#ifdef` with the same condition:
.. code-block:: c++
#ifdef FOO
#ifndef FOO // inner ifndef is considered redundant
void f();
#endif
#endif
* `#ifdef` inside an `#ifndef` with the same condition:
.. code-block:: c++
#ifndef FOO
#ifdef FOO // inner ifdef is considered redundant
void f();
#endif
#endif
* `#if` .. `#endif` pairs which are nested inside an outer pair with the same
condition. For example:
.. code-block:: c++
#define FOO 4
#if FOO == 4
#if FOO == 4 // inner if is considered redundant
void f();
#endif
#endif
.. title:: clang-tidy - readability-redundant-smartptr-get
readability-redundant-smartptr-get
==================================
Find and remove redundant calls to smart pointer's ``.get()`` method.
Examples:
.. code-block:: c++
ptr.get()->Foo() ==> ptr->Foo()
*ptr.get() ==> *ptr
*ptr->get() ==> **ptr
if (ptr.get() == nullptr) ... => if (ptr == nullptr) ...
.. option:: IgnoreMacros
If this option is set to `true` (default is `true`), the check will not warn
about calls inside macros.
.. title:: clang-tidy - readability-redundant-string-cstr
readability-redundant-string-cstr
=================================
Finds unnecessary calls to ``std::string::c_str()`` and ``std::string::data()``.
.. title:: clang-tidy - readability-redundant-string-init
readability-redundant-string-init
=================================
Finds unnecessary string initializations.
Examples
--------
.. code-block:: c++
// Initializing string with empty string literal is unnecessary.
std::string a = "";
std::string b("");
// becomes
std::string a;
std::string b;
// Initializing a string_view with an empty string literal produces an
// instance that compares equal to string_view().
std::string_view a = "";
std::string_view b("");
// becomes
std::string_view a;
std::string_view b;
Options
-------
.. option:: StringNames
Default is `::std::basic_string;::std::basic_string_view`.
Semicolon-delimited list of class names to apply this check to.
By default `::std::basic_string` applies to ``std::string`` and
``std::wstring``. Set to e.g. `::std::basic_string;llvm::StringRef;QString`
to perform this check on custom classes.
.. title:: clang-tidy - readability-simplify-boolean-expr
readability-simplify-boolean-expr
=================================
Looks for boolean expressions involving boolean constants and simplifies
them to use the appropriate boolean expression directly.
Examples:
=========================================== ================
Initial expression Result
------------------------------------------- ----------------
``if (b == true)`` ``if (b)``
``if (b == false)`` ``if (!b)``
``if (b && true)`` ``if (b)``
``if (b && false)`` ``if (false)``
``if (b || true)`` ``if (true)``
``if (b || false)`` ``if (b)``
``e ? true : false`` ``e``
``e ? false : true`` ``!e``
``if (true) t(); else f();`` ``t();``
``if (false) t(); else f();`` ``f();``
``if (e) return true; else return false;`` ``return e;``
``if (e) return false; else return true;`` ``return !e;``
``if (e) b = true; else b = false;`` ``b = e;``
``if (e) b = false; else b = true;`` ``b = !e;``
``if (e) return true; return false;`` ``return e;``
``if (e) return false; return true;`` ``return !e;``
=========================================== ================
The resulting expression ``e`` is modified as follows:
1. Unnecessary parentheses around the expression are removed.
2. Negated applications of ``!`` are eliminated.
3. Negated applications of comparison operators are changed to use the
opposite condition.
4. Implicit conversions of pointers, including pointers to members, to
``bool`` are replaced with explicit comparisons to ``nullptr`` in C++11
or ``NULL`` in C++98/03.
5. Implicit casts to ``bool`` are replaced with explicit casts to ``bool``.
6. Object expressions with ``explicit operator bool`` conversion operators
are replaced with explicit casts to ``bool``.
7. Implicit conversions of integral types to ``bool`` are replaced with
explicit comparisons to ``0``.
Examples:
1. The ternary assignment ``bool b = (i < 0) ? true : false;`` has redundant
parentheses and becomes ``bool b = i < 0;``.
2. The conditional return ``if (!b) return false; return true;`` has an
implied double negation and becomes ``return b;``.
3. The conditional return ``if (i < 0) return false; return true;`` becomes
``return i >= 0;``.
The conditional return ``if (i != 0) return false; return true;`` becomes
``return i == 0;``.
4. The conditional return ``if (p) return true; return false;`` has an
implicit conversion of a pointer to ``bool`` and becomes
``return p != nullptr;``.
The ternary assignment ``bool b = (i & 1) ? true : false;`` has an
implicit conversion of ``i & 1`` to ``bool`` and becomes
``bool b = (i & 1) != 0;``.
5. The conditional return ``if (i & 1) return true; else return false;`` has
an implicit conversion of an integer quantity ``i & 1`` to ``bool`` and
becomes ``return (i & 1) != 0;``
6. Given ``struct X { explicit operator bool(); };``, and an instance ``x`` of
``struct X``, the conditional return ``if (x) return true; return false;``
becomes ``return static_cast<bool>(x);``
Options
-------
.. option:: ChainedConditionalReturn
If `true`, conditional boolean return statements at the end of an
``if/else if`` chain will be transformed. Default is `false`.
.. option:: ChainedConditionalAssignment
If `true`, conditional boolean assignments at the end of an ``if/else
if`` chain will be transformed. Default is `false`.
.. title:: clang-tidy - readability-simplify-subscript-expr
readability-simplify-subscript-expr
===================================
This check simplifies subscript expressions. Currently this covers calling
``.data()`` and immediately doing an array subscript operation to obtain a
single element, in which case simply calling ``operator[]`` suffice.
Examples:
.. code-block:: c++
std::string s = ...;
char c = s.data()[i]; // char c = s[i];
Options
-------
.. option:: Types
The list of type(s) that triggers this check. Default is
`::std::basic_string;::std::basic_string_view;::std::vector;::std::array`
.. title:: clang-tidy - readability-static-accessed-through-instance
readability-static-accessed-through-instance
============================================
Checks for member expressions that access static members through instances, and
replaces them with uses of the appropriate qualified-id.
Example:
The following code:
.. code-block:: c++
struct C {
static void foo();
static int x;
};
C *c1 = new C();
c1->foo();
c1->x;
is changed to:
.. code-block:: c++
C *c1 = new C();
C::foo();
C::x;
.. title:: clang-tidy - readability-static-definition-in-anonymous-namespace
readability-static-definition-in-anonymous-namespace
====================================================
Finds static function and variable definitions in anonymous namespace.
In this case, ``static`` is redundant, because anonymous namespace limits the
visibility of definitions to a single translation unit.
.. code-block:: c++
namespace {
static int a = 1; // Warning.
static const b = 1; // Warning.
}
The check will apply a fix by removing the redundant ``static`` qualifier.
.. title:: clang-tidy - readability-string-compare
readability-string-compare
==========================
Finds string comparisons using the compare method.
A common mistake is to use the string's ``compare`` method instead of using the
equality or inequality operators. The compare method is intended for sorting
functions and thus returns a negative number, a positive number or
zero depending on the lexicographical relationship between the strings compared.
If an equality or inequality check can suffice, that is recommended. This is
recommended to avoid the risk of incorrect interpretation of the return value
and to simplify the code. The string equality and inequality operators can
also be faster than the ``compare`` method due to early termination.
Examples:
.. code-block:: c++
std::string str1{"a"};
std::string str2{"b"};
// use str1 != str2 instead.
if (str1.compare(str2)) {
}
// use str1 == str2 instead.
if (!str1.compare(str2)) {
}
// use str1 == str2 instead.
if (str1.compare(str2) == 0) {
}
// use str1 != str2 instead.
if (str1.compare(str2) != 0) {
}
// use str1 == str2 instead.
if (0 == str1.compare(str2)) {
}
// use str1 != str2 instead.
if (0 != str1.compare(str2)) {
}
// Use str1 == "foo" instead.
if (str1.compare("foo") == 0) {
}
The above code examples shows the list of if-statements that this check will
give a warning for. All of them uses ``compare`` to check if equality or
inequality of two strings instead of using the correct operators.
.. title:: clang-tidy - readability-uniqueptr-delete-release
readability-uniqueptr-delete-release
====================================
Replace ``delete <unique_ptr>.release()`` with ``<unique_ptr> = nullptr``.
The latter is shorter, simpler and does not require use of raw pointer APIs.
.. code-block:: c++
std::unique_ptr<int> P;
delete P.release();
// becomes
std::unique_ptr<int> P;
P = nullptr;
Options
-------
.. option:: PreferResetCall
If `true`, refactor by calling the reset member function instead of
assigning to ``nullptr``. Default value is `false`.
.. code-block:: c++
std::unique_ptr<int> P;
delete P.release();
// becomes
std::unique_ptr<int> P;
P.reset();
.. title:: clang-tidy - readability-uppercase-literal-suffix
readability-uppercase-literal-suffix
====================================
`cert-dcl16-c` redirects here as an alias for this check.
By default, only the suffixes that begin with ``l`` (``l``, ``ll``, ``lu``,
``llu``, but not ``u``, ``ul``, ``ull``) are diagnosed by that alias.
`hicpp-uppercase-literal-suffix` redirects here as an alias for this check.
Detects when the integral literal or floating point (decimal or hexadecimal)
literal has a non-uppercase suffix and provides a fix-it hint with the uppercase
suffix.
All valid combinations of suffixes are supported.
.. code:: c
auto x = 1; // OK, no suffix.
auto x = 1u; // warning: integer literal suffix 'u' is not upper-case
auto x = 1U; // OK, suffix is uppercase.
...
Options
-------
.. option:: NewSuffixes
Optionally, a list of the destination suffixes can be provided. When the
suffix is found, a case-insensitive lookup in that list is made, and if a
replacement is found that is different from the current suffix, then the
diagnostic is issued. This allows for fine-grained control of what suffixes to
consider and what their replacements should be.
Example
^^^^^^^
Given a list `L;uL`:
* ``l`` -> ``L``
* ``L`` will be kept as is.
* ``ul`` -> ``uL``
* ``Ul`` -> ``uL``
* ``UL`` -> ``uL``
* ``uL`` will be kept as is.
* ``ull`` will be kept as is, since it is not in the list
* and so on.
.. option:: IgnoreMacros
If this option is set to `true` (default is `true`), the check will not warn
about literal suffixes inside macros.
.. title:: clang-tidy - readability-use-anyofallof
readability-use-anyofallof
==========================
Finds range-based for loops that can be replaced by a call to ``std::any_of`` or
``std::all_of``. In C++ 20 mode, suggests ``std::ranges::any_of`` or
``std::ranges::all_of``.
Example:
.. code-block:: c++
bool all_even(std::vector<int> V) {
for (int I : V) {
if (I % 2)
return false;
}
return true;
// Replace loop by
// return std::ranges::all_of(V, [](int I) { return I % 2 == 0; });
}
.. title:: clang-tidy - zircon-temporary-objects
zircon-temporary-objects
========================
Warns on construction of specific temporary objects in the Zircon kernel.
If the object should be flagged, If the object should be flagged, the fully
qualified type name must be explicitly passed to the check.
For example, given the list of classes "Foo" and "NS::Bar", all of the
following will trigger the warning:
.. code-block:: c++
Foo();
Foo F = Foo();
func(Foo());
namespace NS {
Bar();
}
With the same list, the following will not trigger the warning:
.. code-block:: c++
Foo F; // Non-temporary construction okay
Foo F(param); // Non-temporary construction okay
Foo *F = new Foo(); // New construction okay
Bar(); // Not NS::Bar, so okay
NS::Bar B; // Non-temporary construction okay
Note that objects must be explicitly specified in order to be flagged,
and so objects that inherit a specified object will not be flagged.
This check matches temporary objects without regard for inheritance and so a
prohibited base class type does not similarly prohibit derived class types.
.. code-block:: c++
class Derived : Foo {} // Derived is not explicitly disallowed
Derived(); // and so temporary construction is okay
Options
-------
.. option:: Names
A semi-colon-separated list of fully-qualified names of C++ classes that
should not be constructed as temporaries. Default is empty.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment