diff --git a/cxx-sensors/src/main/resources/clangtidy.xml b/cxx-sensors/src/main/resources/clangtidy.xml
index 5e416ee6ed..73f33f19db 100644
--- a/cxx-sensors/src/main/resources/clangtidy.xml
+++ b/cxx-sensors/src/main/resources/clangtidy.xml
@@ -3,7 +3,7 @@
C and C++ rules from
* https://clang.llvm.org/extra/clang-tidy/checks/list.html
* https://clang-analyzer.llvm.org/available_checks.html
- * last update: llvmorg-15-init-2831-geb3e09c9bf1d (git describe)
+ * last update: llvmorg-16-init-15404-g61be26154924 (git describe)
-->
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 This check looks for uses of Note: As with other Note: Converting to an integer and back to an References
-]]>
+]]>
References
-]]>
+]]>
absl::Trunc
to perform this operation explicitly instead.References
-]]>
+]]>
absl::Duration
division that is done in a floating-point context, and recommends the use of a function that returns a floating-point value.References
-]]>
+]]>
References
-]]>
+]]>
References
-]]>
+]]>
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.References
-]]>
+]]>
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.References
-]]>
+]]>
References
-]]>
+]]>
clang-tidy - 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 because 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:
@@ -373,7 +375,7 @@ class foo { absl::memory_internal::MakeUniqueResult(); // warning triggered on this linewill be prompted with a warning.
See the full Abseil compatibility guidelines for more information.
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.
The location of Abseil's strings/match.h
. Defaults to absl/strings/match.h
.
The location of Abseil's strings/match.h
. Defaults to absl/strings/match.h
.
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.
Based on the Altera SDK for OpenCL: Best Practices Guide.
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.
Defines the version of the Altera Offline Compiler. Defaults to 1600
(corresponding to version 16.00).
In practice, this refers to the integer value of the upper bound within the loop statement's condition expression.
Suggested replacement:
pipe2(pipefd, O_CLOEXEC);
Suggested replacement:
pipe2(pipefd, O_NONBLOCK | O_CLOEXEC);
A comma-separated list of the names of retry macros to be checked.
A semicolon-separated list of the names of functions or methods to be considered as not having side-effects. 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).
This check corresponds to the CERT C Coding Standard rule POS44-C. Do not use signals to terminate threads.
Unlike if statements, the check does not detect chains of conditional operators.
Note: This check also reports situations where branches become identical only after preprocessing.
The check also suggests a fix-its in some cases.
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.
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.
Comma separated list containing type names which are not counted as thrown exceptions in the check. Default value is an empty string.
auto a = {65536LL * 65536 * 65536};
return std::accumulate(std::begin(a), std::end(a), 0);
This check can only generate warnings, but it can't suggest a fix at this point.
For deciding whether a constructor is guarded with enable_if, we consider the types of the constructor parameters, the default values of template type parameters and the types of non-type template parameters with a default literal value. If any part of these types is std::enable_if
or std::enable_if_t
, we assume the constructor is guarded.
Called from FancyFunction
Now called from FancyFunction
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.
Checks for repeated argument with side effects in macros.
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
char *p = (char*) malloc(n + 10);
If true, enables detection of implicit casts. Default is false.
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.
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.
This will never happen as the return value is always non-negative. A simple fix could be:
if (posix_fadvise(...) > 0) {
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.
+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 as well as its C++ counterpart, DCL51-CPP. Do not declare or define a reserved identifier.
Semicolon-separated list of names that the check ignores. Default is an empty list.
This check partially covers the CERT C++ Coding Standard rule MEM51-CPP. Properly deallocate dynamically allocated resources However, only the std::shared_ptr
case is detected by this check.
clang-tidy - 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 and has an alias name cert-sig30-c
.
Finds specific constructs in signal handler functions that can cause undefined behavior. The rules for what is allowed differ between C++ language versions.
+Checked signal handler rules for C:
+Checked signal handler rules for up to and including C++14:
+The check is disabled on C++17 and later.
+Asnychronous-safety is determined by comparing the function's name against a set of known functions. In addition, the function must come from a system header include and in a global namespace. The (possible) arguments passed to the function are not checked. Any function that cannot be determined to be asynchronous-safe is assumed to be non-asynchronous-safe by the check, including user functions for which only the declaration is visible. Calls to user-defined functions with visible definitions are checked recursively.
+This check implements the CERT C Coding Standard rule SIG30-C. Call only asynchronous-safe functions within signal handlers and the rule MSC54-CPP. A signal handler must be a plain old function. It has the alias names cert-sig30-c
and cert-msc54-cpp
.
AsyncSafeFunctionSet
-Selects which 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 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
.
Selects which set of functions is considered as asynchronous-safe (and therefore allowed in signal handlers). It can be set to the following values:
+minimal
Selects a minimal set that is defined in the CERT SIG30-C rule. and includes functions abort()
, _Exit()
, quick_exit()
and signal()
.
POSIX
Selects a larger set of functions that is listed in POSIX.1-2017 (see this link for more information). The following functions are included: _Exit
, _exit
, abort
, accept
, access
, aio_error
, aio_return
, aio_suspend
, alarm
, bind
, cfgetispeed
, cfgetospeed
, cfsetispeed
, cfsetospeed
, chdir
, chmod
, chown
, clock_gettime
, close
, connect
, creat
, dup
, dup2
, execl
, execle
, execv
, execve
, faccessat
, fchdir
, fchmod
, fchmodat
, fchown
, fchownat
, fcntl
, fdatasync
, fexecve
, ffs
, fork
, fstat
, fstatat
, fsync
, ftruncate
, futimens
, getegid
, geteuid
, getgid
, getgroups
, getpeername
, getpgrp
, getpid
, getppid
, getsockname
, getsockopt
, getuid
, htonl
, htons
, kill
, link
, linkat
, listen
, longjmp
, lseek
, lstat
, memccpy
, memchr
, memcmp
, memcpy
, memmove
, memset
, mkdir
, mkdirat
, mkfifo
, mkfifoat
, mknod
, mknodat
, ntohl
, ntohs
, open
, openat
, pause
, pipe
, poll
, posix_trace_event
, pselect
, pthread_kill
, pthread_self
, pthread_sigmask
, quick_exit
, raise
, read
, readlink
, readlinkat
, recv
, recvfrom
, recvmsg
, rename
, renameat
, rmdir
, select
, sem_post
, send
, sendmsg
, sendto
, setgid
, setpgid
, setsid
, setsockopt
, setuid
, shutdown
, sigaction
, sigaddset
, sigdelset
, sigemptyset
, sigfillset
, sigismember
, siglongjmp
, signal
, sigpause
, sigpending
, sigprocmask
, sigqueue
, sigset
, sigsuspend
, sleep
, sockatmark
, socket
, socketpair
, stat
, stpcpy
, stpncpy
, strcat
, strchr
, strcmp
, strcpy
, strcspn
, strlen
, strncat
, strncmp
, strncpy
, strnlen
, strpbrk
, strrchr
, strspn
, strstr
, strtok_r
, symlink
, symlinkat
, tcdrain
, tcflow
, tcflush
, tcgetattr
, tcgetpgrp
, tcsendbreak
, tcsetattr
, tcsetpgrp
, time
, timer_getoverrun
, timer_gettime
, timer_settime
, times
, umask
, uname
, unlink
, unlinkat
, utime
, utimensat
, utimes
, wait
, waitpid
, wcpcpy
, wcpncpy
, wcscat
, wcschr
, wcscmp
, wcscpy
, wcscspn
, wcslen
, wcsncat
, wcsncmp
, wcsncpy
, wcsnlen
, wcspbrk
, wcsrchr
, wcsspn
, wcsstr
, wcstok
, wmemchr
, wmemcmp
, wmemcpy
, wmemmove
, wmemset
, write
The function quick_exit
is not included in the POSIX list but it is included here in the set of safe functions.
The default value is POSIX
.
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
-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.
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 below. This code stops not only when it reaches the end of the file, but also when it gets a character with the 255 code.
#define EOF (-1)
int read(void) {
@@ -2582,7 +2607,7 @@ int read(void) {
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.
References
-]]>
+]]>
MINOR
BUG
@@ -2611,7 +2636,7 @@ int c = sizeof(array_of_strings) / sizeof(array_of_strings[0]); // no warning, d
std::array<int, 3> std_array;
int d = sizeof(std_array); // no warning, probably intended.
WarnOnSizeOfCompareToConstant
When true, the check will warn on an expression like sizeof(expr) <= k
for a suspicious constant k while k is 0 or greater than 0x8000. Default is true.
WarnOnSizeOfPointerToAggregate
+When true, the check will warn on an expression like sizeof(expr) where the expression is a pointer to aggregate. Default is `true.
+This check corresponds to the CERT C++ Coding Standard rule 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.
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.
std::string s;
s = static_cast<char>(6);
The source pattern with trailing comment "B" selects the (const CharT*, size_type)
constructor which is perfectly valid, since the length argument is 0
. It is not changed by this ClangTidy check.
Default value: 0. When non-null the suspicious bitmask usage will be investigated additionally to the different enum usage check.
Default value: "c;cc;cpp;cxx"
Likewise, a semicolon-separated list of filename extensions of implementation files.
See also: EXP42-C. Do not compare padding data and FLP37-C. Do not use object representations to compare floating-point values
This check is also related to and partially overlaps the CERT C++ Coding Standard rules OOP57-CPP. Prefer special member functions and overloaded operators to C Standard Library functions and EXP62-CPP. Do not access the bits of an object representation that are not part of the object's value representation
5U
.
In this case the check will assume that you know what you are doing, and will not raise a warning.
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.
Finds potentially swapped arguments by looking at implicit conversions.
Finds calls of memory manipulation functions memset()
, memcpy()
and memmove()
on not TriviallyCopyable objects resulting in undefined behavior.
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.
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.
std::basic_string::empty()
and std::vector::empty()
. Not using the return value often indicates that the programmer confused the function with clear()
.cert-err33-c is an alias of this check that checks a fixed and large set of standard library functions.
+cert-err33-c is an alias of this check that checks a fixed and large set of standard library functions.
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.
clang-tidy - cert-con36-c
- - - - - - -Modification of the std
or posix
namespace can result in undefined behavior. This check warns for such modifications.
Modification of the std
or posix
namespace can result in undefined behavior. This check warns for such modifications. The std
(or posix
) namespace is allowed to be extended with (class or function) template specializations that depend on an user-defined type (a type that is not defined in the standard system headers).
The check detects the following (user provided) declarations in namespace std
or posix
:
Examples:
namespace std {
- int x; // May cause undefined behavior.
+ int x; // warning: modification of 'std' namespace can result in undefined behavior [cert-dcl58-cpp]
+}
+namespace posix::a { // warning: modification of 'posix' namespace can result in undefined behavior
+}
+template <>
+struct ::std::hash<long> { // warning: modification of 'std' namespace can result in undefined behavior
+ unsigned long operator()(const long &K) const {
+ return K;
+ }
+};
+struct MyData { long data; };
+template <>
+struct ::std::hash<MyData> { // no warning: specialization with user-defined type
+ unsigned long operator()(const MyData &K) const {
+ return K.data;
+ }
+};
+namespace std {
+ template <>
+ void swap<bool>(bool &a, bool &b); // warning: modification of 'std' namespace can result in undefined behavior
+ template <>
+ bool less<void>::operator()<MyData &&, MyData &&>(MyData &&, MyData &&) const { // warning: modification of 'std' namespace can result in undefined behavior
+ return true;
+ }
}
This check corresponds to the CERT C++ Coding Standard rule DCL58-CPP. Do not modify the standard namespaces.
clang-tidy - cert-dcl59-cpp
- -Warns on unused function return values. Many of the standard library functions return a value that indicates if the call was successful. Ignoring the returned value can cause unexpected behavior if an error has occured. The following functions are checked:
+Warns on unused function return values. Many of the standard library functions return a value that indicates if the call was successful. Ignoring the returned value can cause unexpected behavior if an error has occurred. The following functions are checked:
This check is an alias of check bugprone-unused-return-value with a fixed set of functions.
+This check is an alias of check bugprone-unused-return-value with a fixed set of functions.
The check corresponds to a part of CERT C Coding Standard rule ERR33-C. Detect and handle standard library errors. The list of checked functions is taken from the rule, with following exception:
NULL
argument. Therefore the following functions are not checked: mblen
, mbrlen
, mbrtowc
, mbtowc
, wctomb
, wctomb_s
This check corresponds to the CERT C Coding Standard rule ERR34-C. Detect errors when converting a string to a number.
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().
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.
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.
clang-tidy - cert-err61-cpp
-The cert-exp42-c check is an alias, please see bugprone-suspicious-memory-comparison for more information.
+The cert-exp42-c check is an alias, please see bugprone-suspicious-memory-comparison for more information.
clang-tidy - cert-fio38-c
-The cert-flp37-c check is an alias, please see bugprone-suspicious-memory-comparison for more information.
+The cert-flp37-c check is an alias, please see bugprone-suspicious-memory-comparison for more information.
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.
clang-tidy - cert-msc30-c
- -clang-tidy - cert-oop11-cpp
- -This check corresponds to the CERT C++ Coding Standard rule OOP57-CPP. Prefer special member functions and overloaded operators to C Standard Library functions.
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.
clang-tidy - cert-pos44-c
- - - -This check corresponds to the CERT C Coding Standard rule POS47-C. Do not use threads that can be canceled asynchronously.
clang-tidy - cppcoreguidelines-avoid-c-arrays
- - - -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.
Boolean flag to toggle ignoring command-line-defined macros. Default value is true.
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.
Semicolon-separated list of fully qualified names of memory allocation functions. Defaults to ::realloc
.
clang-tidy - cppcoreguidelines-non-private-member-variables-in-classes
-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.
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.
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.
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.
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.
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.
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.
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.
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
The corresponding information about the problem of OSSpinlock
: https://blog.postmates.com/why-spinlocks-are-bad-on-ios-b69fc5221058
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 for more information.
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
will cause a warning.
See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md
clang-tidy - fuchsia-header-anon-namespaces
-Corresponding cpplint.py check name: build/namespaces.
Checks that default arguments are not given for virtual methods.
See https://google.github.io/styleguide/cppguide.html#Default_Arguments
See https://google.github.io/styleguide/cppguide.html#Explicit_Constructors
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).
This check corresponds to the Google Objective-C Style Guide rule Do Not Use +new.
The corresponding style guide rule: https://google.github.io/styleguide/objcguide.html#avoid-throwing-exceptions
static bool IsPositive(int i) { return i > 0; }
bool *ABCIsNegative(int i) { return i < 0; }
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.
For example:
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.
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.
clang-tidy - google-readability-braces-around-statements
- - -https://google.github.io/styleguide/cppguide.html#Operator_Overloading
Corresponding cpplint.py check name: runtime/operator.
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 only a warning when a fix cannot be made safely, as is the case with some template and macro uses.
clang-tidy - hicpp-avoid-c-arrays
-The hicpp-avoid-goto check is an alias to cppcoreguidelines-avoid-goto. Rule 6.3.1 High Integrity C++ requires that goto
only skips parts of a block and is not used for other reasons.
The hicpp-avoid-goto check is an alias to cppcoreguidelines-avoid-goto. Rule 6.3.1 High Integrity C++ 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
.
clang-tidy - hicpp-braces-around-statements
- - - - - - -clang-tidy - hicpp-named-parameter
- - - - -clang-tidy - hicpp-special-member-functions
- - - - - - - - - - - - -clang-tidy - llvm-qualified-auto
-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).
+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).
UseHeaderFileExtension
When true, the check will use the file extension to distinguish header files. Default is true.
An example of such misleading code follows:
#include <stdio.h>
-short int = (short int)0;
-short int = (short int)12345;
+short int N = (short int)0;
+short int l = (short int)12345;
int main() {
- int = ; // a local variable, set to zero?
- printf(" is %d\n", );
- printf(" is %d\n", );
+ int N = N; // a local variable, set to zero?
+ printf("l is %d\n", l);
+ printf("N is %d\n", N);
}
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.
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.
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.
Allows to ignore (not diagnose) all the member variables declared with a public
access specifier.
Replaces assert()
with static_assert()
if the condition is evaluable at compile time.
The condition of static_assert()
is evaluated at compile time which is safer and more efficient.
char
, wchar_t
, unicode character types) will not be flagged to allow catching sting literals.char
, wchar_t
, unicode character types) will not be flagged to allow catching string literals.throw;
it happens often enough in real code.Determines the maximum size of an object allowed to be caught without warning. Only applicable if 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.
A string specifying which include-style is used, llvm or google. Default is llvm.
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.
namespace n { class C; }
using n::C; // Never actually used.
which is correct.
This check requires using C++14 or higher to run.
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<>
.
Similarly, the main()
function is ignored. Its second and third parameters can be either char* argv[]
or char** argv
, but cannot be std::array<>
.
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.
+// C++ source file...
+#include <assert.h>
+#include <stdbool.h>
+
+// becomes
+
+#include <cassert>
+// No 'stdbool.h' here.
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.
The checker ignores include directives within extern "C" { ... } blocks, since a library might want to expose some API for C and C++ libraries.
+// C++ source file...
+extern "C" {
+#include <assert.h> // Left intact.
+#include <stdbool.h> // Left intact.
+}
+CheckHeaderFile
+clang-tidy cannot know if the header file included by the currently analyzed C++ source file is not included by any other C source files. Hence, to omit false-positives and wrong fixit-hints, we ignore emitting reports into header files. One can set this option to true if they know that the header files in the project are only used by C++ source file. Default is false.
+As range-based for loops are only available since OpenMP 5, this check should not be used on code with a compatibility requirement 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 clang-tidy-nolint
) on the specific for loops is recommended.
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.
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.
For more information about the pass-by-value idiom, read: Want Speed? Pass by Value.
+For more information about the pass-by-value idiom, read: Want Speed? Pass by Value.
When true, the check only warns about copied parameters that are already passed by value. Default is false.
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.
A string specifying which include-style is used, llvm or google. Default is llvm.
private
access specification untouched. You might want to run the check modernize-use-equals-delete
-<modernize-use-equals-delete>
to get warnings for deleted functions in private sections.See: https://en.cppreference.com/w/cpp/language/function#Deleted_functions
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.
If set to true, the check will not give warnings inside macros. Default is true.
If this option is set to true (default is true), the check will not warn about members declared inside macros.
clang-tidy - modernize-use-default
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, 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 ContainersWithPushBack
option.
The check flags insertions to an STL-style container done by calling the push_back
, push
, or push_front
methods with an explicitly-constructed temporary of the container element type. In this case, the corresponding emplace
equivalent methods result in less verbose and potentially more efficient code. Right now the check doesn't support insert
. It also doesn't support insert
functions for associative containers because replacing insert
with emplace
may result in speed regression, but it might get support with some addition flag in the future.
The ContainersWithPushBack
, ContainersWithPush
, and ContainersWithPushFront
options are used to specify the container types that support the push_back
, push
, and push_front
operations respectively. The default values for these options are as follows:
ContainersWithPushBack
: std::vector
, std::deque
, and std::list
.ContainersWithPush
: std::stack
, std::queue
, and std::priority_queue
.ContainersWithPushFront
: std::forward_list
, std::list
, and std::deque
.This check also reports when an emplace
-like method is improperly used, for example using emplace_back
while also calling a constructor. This creates a temporary that requires at best a move and at worst a copy. Almost all emplace
-like functions in the STL are covered by this, with try_emplace
on std::map
and std::unordered_map
being the exception as it behaves slightly differently than all the others. More containers can be added with the EmplacyFunctions
option, so long as the container defines a value_type
type, and the emplace
-like functions construct a value_type
object.
Before:
std::vector<MyClass> v;
v.push_back(MyClass(21, 37));
+v.emplace_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));
+w.push_back(std::make_pair(21L, 37L));
+w.emplace_back(std::make_pair(21L, 37L));
After:
std::vector<MyClass> v;
v.emplace_back(21, 37);
+v.emplace_back(21, 37);
std::vector<std::pair<int, int>> w;
w.emplace_back(21, 37);
+w.emplace_back(21L, 37L);
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 TupleTypes
option; custom make functions can be modified by the TupleMakeFunctions
option.
The other situation is when we pass arguments that will be converted to a type inside a container.
@@ -10390,6 +10480,14 @@ v.push_back(std::unique_ptr<int>(ptr));Semicolon-separated list of class names of custom containers that support push_back
.
ContainersWithPush
+Semicolon-separated list of class names of custom containers that support push
.
ContainersWithPushFront
+Semicolon-separated list of class names of custom containers that support push_front
.
IgnoreImplicitConstructors
When true, the check will ignore implicitly constructed arguments of push_back
, e.g.
std::vector<std::string> v;
@@ -10408,15 +10506,21 @@ v.push_back("a"); // Ignored when IgnoreImplicitConstructors is `true`
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
.
EmplacyFunctions
+Semicolon-separated list of containers without their template parameters and some emplace
-like method of the container. Example: vector::emplace_back
. Those methods will be checked for improper use and the check will report when a temporary is unnecessarily created.
std::vector<MyTuple<int, bool, char>> x;
-x.push_back(MakeMyTuple(1, false, 'x'));
+x.push_back(MakeMyTuple(1, false, 'x'));
+x.emplace_back(MakeMyTuple(1, false, 'x'));
transforms to:
std::vector<MyTuple<int, bool, char>> x;
+x.emplace_back(1, false, 'x');
x.emplace_back(1, false, 'x');
-when TupleTypes
is set to MyTuple
and TupleMakeFunctions
is set to MakeMyTuple
.
when TupleTypes
is set to MyTuple
, TupleMakeFunctions
is set to MakeMyTuple
, and EmplacyFunctions
is set to vector::emplace_back
.
If set to true, the check will not give warnings inside macros. Default is true.
If this option is set to true (default is true), the check will not warn about functions declared inside macros.
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
if the UseNoexceptFalse
option is set to false.
if the NullMacros
option is set to MY_NULL
.
For more information on the use of override
see https://en.cppreference.com/w/cpp/language/override
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.
This check requires using C++14 or higher to run.
If set to true, the check will not give warnings inside macros. Default is true.
Finds improper usages of XCTAssertEqual and XCTAssertNotEqual and replaces them with XCTAssertEqualObjects or XCTAssertNotEqualObjects.
This makes tests less fragile, as many improperly rely on pointer equality for strings that have equal values. This assumption is not guarantted by the language.
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
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.
Defaults to ABNewPersonViewController;ABPeoplePickerNavigationController;ABPersonViewController;ABUnknownPersonViewController;NSHashTable;NSMapTable;NSPointerArray;NSPointerFunctions;NSTimer;UIActionSheet;UIAlertView;UIImagePickerController;UITextInputMode;UIWebView.
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.
// "id _returnValue" is declaration of instance variable of class.
[invocation getReturnValue:&self->_returnValue];
@property(nonatomic, assign) int abc_lowerCamelCase;
The corresponding style rule: https://developer.apple.com/library/content/qa/qa1908/_index.html
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.
Comma-separated list containing type names which are not counted as thrown exceptions in the check. Default value is an empty string.
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.
// ``for`` directive can not have ``default`` clause, no diagnostics.
+// ``for`` directive cannot have ``default`` clause, no diagnostics.
void n0(const int a) {
#pragma omp for
for (int b = 0; b < a; b++)
@@ -11190,7 +11294,7 @@ void p0_3() {
// clause. Consider using ``default(none)`` clause instead.
}
References
-]]>
+]]>
INFO
CODE_SMELL
@@ -11216,7 +11320,7 @@ str.find('A');
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.
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).
clang-tidy - performance-implicit-cast-in-loop
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.
If true, enables detection of std::move() passed as a const reference argument. Default is true.
"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.
In that case the fix is more consensual: just return std::move(obj). This is handled by the -Wreturn-std-move warning.
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.
A semicolon-separated list of names of types whose methods are allowed to return the const reference the variable is copied from. When an expensive to copy variable is copy initialized by the return value from a type on this list the check does not trigger. This can be used to exclude types known to be const incorrect or where the lifetime or immutability of returned references is not tied to mutations of the container. An example are view types that don't own the underlying data. Like for AllowedTypes above, regular expressions are accepted and the inclusion of :: determines whether the qualified typename is matched or not.
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).
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.
The namespace used to suggest P0214 alternatives. If not specified, std:: for -std=c++20 and std::experimental:: for -std=c++11.
Examples:
void f(const string); // Bad: const is top level.
void f(const string&); // Good: const is not top level.
+IgnoreMacros
+If set to true, the check will not give warnings inside macros. Default is true.
+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).
const int* foo();
const int& foo();
const Clazz* foo();
+IgnoreMacros
+If set to true, the check will not give warnings inside macros. Default is true.
+This check applies to std::set
, std::unordered_set
, std::map
, std::unordered_map
and the corresponding multi-key variants. It is only active for C++20 and later, as the contains
method was only added in C++20.
Finds cases where code could use data()
rather than the address of the element at index 0 in a container. This pattern is commonly used to materialize a pointer to the backing data of a container. std::vector
and std::string
provide a data()
accessor to retrieve the data pointer which should be preferred.
This also ensures that in the case that the container is empty, the data pointer access does not perform an errant memory access.
size_type can be any kind of integer type.
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 to replace calls like Instance.method()
by Class::method()
.
After making a member function static
, you might want to run the check readability-static-accessed-through-instance to replace calls like Instance.method()
by Class::method()
.
clang-tidy - readability-data-pointer
- -Finds cases where code could use data()
rather than the address of the element at index 0 in a container. This pattern is commonly used to materialize a pointer to the backing data of a container. std::vector
and std::string
provide a data()
accessor to retrieve the data pointer which should be preferred.
This also ensures that in the case that the container is empty, the data pointer access does not perform an errant memory access.
-#undef NDEBUG
#include "assertion.h"
// ...code with assertions enabled
+
#define NDEBUG
#include "assertion.h"
// ...code with assertions disabled
There is an alias of this check called llvm-else-after-return. In that version the options WarnOnUnfixable
and WarnOnConditionVariables
are both set to false by default.
This check helps to enforce this LLVM Coding Standards recommendation.
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.
clang-tidy - readability-implicit-bool-cast
If this option is set to true (default is false), then names must match exactly (or be absent).
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.
const_cast
this
at all (see readability-convert-member-functions-to-static).this
at all (see readability-convert-member-functions-to-static).The following real-world examples will be preserved by the check:
class E1 {
@@ -14949,7 +15050,7 @@ public:
};
After applying modifications as suggested by the check, running the check again might find more opportunities to mark member functions const
.
Note that this check only works as expected when the tabs or spaces are used consistently and not mixed.
All parameters should be named, with identical names in the declaration and implementation.
Corresponding cpplint.py check name: readability/function.
Note in the LLVM alias, the default value is false.
If CheckFirstDeclaration option is enabled, a warning about redundant access specifier will be emitted, because public
is the default member access for structs.
If set to true, the check will not give warnings inside macros. Default is true.
If this option is set to true (default is true), the check will not warn about calls inside macros.
Finds unnecessary calls to std::string::c_str()
and std::string::data()
.
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.
clang-tidy - readability-simplify-boolean-expr
Looks for boolean expressions involving boolean constants and simplifies them to use the appropriate boolean expression directly.
+Looks for boolean expressions involving boolean constants and simplifies them to use the appropriate boolean expression directly. Simplifies boolean expressions by application of DeMorgan's Theorem.
Examples:
!(!a || b) |
++ |
+
!(a || !b) |
++ |
+
!(!a || !b) |
++ |
+
!(!a && b) |
++ |
+
!(a && !b) |
++ |
+
!(!a && !b) |
++ |
+
ChainedConditionalAssignment
If true, conditional boolean assignments at the end of an if/else if
chain will be transformed. Default is false.
SimplifyDeMorgan
+If true, DeMorgan's Theorem will be applied to simplify negated conjunctions and disjunctions. Default is true.
+SimplifyDeMorganRelaxed
+If true, SimplifyDeMorgan
will also transform negated conjunctions and disjunctions where there is no negation on either operand. This option has no effect if SimplifyDeMorgan
is false. Default is false.
When Enabled:
+bool X = !(A && B)
+bool Y = !(A || B)
+Would be transformed to:
+bool X = !A || !B
+bool Y = !A && !B
+The list of type(s) that triggers this check. Default is ::std::basic_string;::std::basic_string_view;::std::vector;::std::array
The check will apply a fix by removing the redundant static
qualifier.
The above code examples show 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.
Common abbreviations can be specified which will deem the strings similar if the abbreviated and the abbreviation stand together. For example, if src
is registered as an abbreviation for source
, then the following code example will be warned about.
void foo(int source, int x);
+
foo(b, src);
The abbreviations to recognise can be configured with the Abbreviations<opt_Abbreviations>
check option. This heuristic is case-insensitive.
The Levenshtein distance describes how many single-character changes (additions, changes, or removals) must be applied to transform one string into another.
The Levenshtein distance is translated into a similarity percentage by dividing it with the length of the longer string, and taking its complement with regards to 100%. For example, given something
and anything
, the distance is 4 edits, and the similarity percentage is 100% - 4 / 9 = 55.55...%.
This heuristic can be configured with bounds<opt_Bounds>
. The default bounds are: below 50% dissimilar and above 66% similar. This heuristic is case-sensitive.
The Jaro-Winkler distance is an edit distance like the Levenshtein distance. It is calculated from the amount of common characters that are sufficiently close to each other in position, and to-be-changed characters. The original definition of Jaro has been extended by Winkler to weigh prefix similarities more. The similarity percentage is expressed as an average of the common and non-common characters against the length of both strings.
+The Jaro--Winkler distance is an edit distance like the Levenshtein distance. It is calculated from the amount of common characters that are sufficiently close to each other in position, and to-be-changed characters. The original definition of Jaro has been extended by Winkler to weigh prefix similarities more. The similarity percentage is expressed as an average of the common and non-common characters against the length of both strings.
This heuristic can be configured with bounds<opt_Bounds>
. The default bounds are: below 75% dissimilar and above 85% similar. This heuristic is case-insensitive.
The Sorensen-Dice coefficient was originally defined to measure the similarity of two sets. Formally, the coefficient is calculated by dividing 2 * #(intersection) with #(set1) + #(set2), where #() is the cardinality function of sets. This metric is applied to strings by creating bigrams (substring sequences of length 2) of the two strings and using the set of bigrams for the two strings as the two sets.
+The Sorensen--Dice coefficient was originally defined to measure the similarity of two sets. Formally, the coefficient is calculated by dividing 2 * #(intersection) with #(set1) + #(set2), where #() is the cardinality function of sets. This metric is applied to strings by creating bigrams (substring sequences of length 2) of the two strings and using the set of bigrams for the two strings as the two sets.
This heuristic can be configured with bounds<opt_Bounds>
. The default bounds are: below 60% dissimilar and above 70% similar. This heuristic is case-insensitive.
Empty argument or parameter names are ignored by the heuristics.
If this option is set to true (default is true), the check will not warn about literal suffixes inside macros.
A semi-colon-separated list of fully-qualified names of C++ classes that should not be constructed as temporaries. Default is empty.
clang-tidy - abseil-cleanup-ctad
+ +Suggests switching the initialization pattern of absl::Cleanup
instances from the factory function to class template argument deduction (CTAD), in C++17 and higher.
auto c1 = absl::MakeCleanup([] {});
+
+const auto c2 = absl::MakeCleanup(std::function<void()>([] {}));
+becomes
+absl::Cleanup c1 = [] {};
+
+const absl::Cleanup c2 = std::function<void()>([] {});
+clang-tidy - bugprone-assignment-in-if-condition
+ +Finds assignments within conditions of if statements. Such assignments are bug-prone because they may have been intended as equality tests.
+This check finds all assignments within if conditions, including ones that are not flagged by -Wparentheses due to an extra set of parentheses, and including assignments that call an overloaded operator=(). The identified assignments violate BARR group "Rule 8.2.c".
+int f = 3;
+if(f = 4) { // This is identified by both `Wparentheses` and this check - should it have been: `if (f == 4)` ?
+ f = f + 1;
+}
+
+if((f == 5) || (f = 6)) { // the assignment here `(f = 6)` is identified by this check, but not by `-Wparentheses`. Should it have been `(f == 6)` ?
+ f = f + 2;
+}
+clang-tidy - bugprone-narrowing-conversions
+ + +The bugprone-narrowing-conversions check is an alias, please see cppcoreguidelines-narrowing-conversions for more information.
+clang-tidy - bugprone-standalone-empty
+ +Warns when empty() is used on a range and the result is ignored. Suggests clear() if it is an existing member function.
+The empty()
method on several common ranges returns a Boolean indicating whether or not the range is empty, but is often mistakenly interpreted as a way to clear the contents of a range. Some ranges offer a clear()
method for this purpose. This check warns when a call to empty returns a result that is ignored, and suggests replacing it with a call to clear()
if it is available as a member function of the range.
For example, the following code could be used to indicate whether a range is empty or not, but the result is ignored:
+std::vector<int> v;
+...
+v.empty();
+A call to clear()
would appropriately clear the contents of the range:
std::vector<int> v;
+...
+v.clear();
+clang-tidy - bugprone-suspicious-realloc-usage
+ +This check finds usages of realloc
where the return value is assigned to the same expression as passed to the first argument: p = realloc(p, size);
The problem with this construct is that if realloc
fails it returns a null pointer but does not deallocate the original memory. If no other variable is pointing to it, the original memory block is not available any more for the program to use or free. In either case p = realloc(p, size);
indicates bad coding style and can be replaced by q = realloc(p, size);
.
The pointer expression (used at realloc
) can be a variable or a field member of a data structure, but can not contain function calls or unresolved types.
In obvious cases when the pointer used at realloc is assigned to another variable before the realloc
call, no warning is emitted. This happens only if a simple expression in form of q = p
or void *q = p
is found in the same function where p = realloc(p, ...)
is found. The assignment has to be before the call to realloc (but otherwise at any place) in the same function. This suppression works only if p
is a single variable.
Examples:
+struct A {
+ void *p;
+};
+
+A &getA();
+
+void foo(void *p, A *a, int new_size) {
+ p = realloc(p, new_size); // warning: 'p' may be set to null if 'realloc' fails, which may result in a leak of the original buffer
+ a->p = realloc(a->p, new_size); // warning: 'a->p' may be set to null if 'realloc' fails, which may result in a leak of the original buffer
+ getA().p = realloc(getA().p, new_size); // no warning
+}
+
+void foo1(void *p, int new_size) {
+ void *p1 = p;
+ p = realloc(p, new_size); // no warning
+}
+clang-tidy - bugprone-unchecked-optional-access
+ +Note: This check uses a flow-sensitive static analysis to produce its results. Therefore, it may be more resource intensive (RAM, CPU) than the average clang-tidy check.
+This check identifies unsafe accesses to values contained in std::optional<T>
, absl::optional<T>
, or base::Optional<T>
objects. Below we will refer to all these types collectively as optional<T>
.
An access to the value of an optional<T>
occurs when one of its value
, operator*
, or operator->
member functions is invoked. To align with common misconceptions, the check considers these member functions as equivalent, even though there are subtle differences related to exceptions versus undefined behavior. See go/optional-style-recommendations for more information on that topic.
An access to the value of an optional<T>
is considered safe if and only if code in the local scope (for example, a function body) ensures that the optional<T>
has a value in all possible execution paths that can reach the access. That should happen either through an explicit check, using the optional<T>::has_value
member function, or by constructing the optional<T>
in a way that shows that it unambiguously holds a value (e.g using std::make_optional
which always returns a populated std::optional<T>
).
Below we list some examples, starting with unsafe optional access patterns, followed by safe access patterns.
+The check flags accesses to the value that are not locally guarded by existence check:
+void f(std::optional<int> opt) {
+ use(*opt); // unsafe: it is unclear whether `opt` has a value.
+}
+The check is aware of the state of an optional object in different branches of the code. For example:
+void f(std::optional<int> opt) {
+ if (opt.has_value()) {
+ } else {
+ use(opt.value()); // unsafe: it is clear that `opt` does *not* have a value.
+ }
+}
+The check is aware that function results might not be stable. That is, consecutive calls to the same function might return different values. For example:
+void f(Foo foo) {
+ if (foo.opt().has_value()) {
+ use(*foo.opt()); // unsafe: it is unclear whether `foo.opt()` has a value.
+ }
+}
+The check is unaware of invariants of uncommon APIs. For example:
+void f(Foo foo) {
+ if (foo.HasProperty("bar")) {
+ use(*foo.GetProperty("bar")); // unsafe: it is unclear whether `foo.GetProperty("bar")` has a value.
+ }
+}
+The check relies on local reasoning. The check and value access must both happen in the same function. An access is considered unsafe even if the caller of the function performing the access ensures that the optional has a value. For example:
+void g(std::optional<int> opt) {
+ use(*opt); // unsafe: it is unclear whether `opt` has a value.
+}
+
+void f(std::optional<int> opt) {
+ if (opt.has_value()) {
+ g(opt);
+ }
+}
+The check recognizes all straightforward ways for checking if a value exists and accessing the value contained in an optional object. For example:
+void f(std::optional<int> opt) {
+ if (opt.has_value()) {
+ use(*opt);
+ }
+}
+The criteria that the check uses is semantic, not syntactic. It recognizes when a copy of the optional object being accessed is known to have a value. For example:
+void f(std::optional<int> opt1) {
+ if (opt1.has_value()) {
+ std::optional<int> opt2 = opt1;
+ use(*opt2);
+ }
+}
+The check is aware of common macros like CHECK
, DCHECK
, and ASSERT_THAT
. Those can be used to ensure that an optional object has a value. For example:
void f(std::optional<int> opt) {
+ DCHECK(opt.has_value());
+ use(*opt);
+}
+The check is aware of correlated branches in the code and can figure out when an optional object is ensured to have a value on all execution paths that lead to an access. For example:
+void f(std::optional<int> opt) {
+ bool safe = false;
+ if (opt.has_value() && SomeOtherCondition()) {
+ safe = true;
+ }
+ // ... more code...
+ if (safe) {
+ use(*opt);
+ }
+}
+Since function results are not assumed to be stable across calls, it is best to store the result of the function call in a local variable and use that variable to access the value. For example:
+void f(Foo foo) {
+ if (const auto& foo_opt = foo.opt(); foo_opt.has_value()) {
+ use(*foo_opt);
+ }
+}
+When uncommon APIs guarantee that an optional has contents, do not rely on it --instead, check explicitly that the optional object has a value. For example:
+void f(Foo foo) {
+ if (const auto& property = foo.GetProperty("bar")) {
+ use(*property);
+ }
+}
+instead of the HasProperty, GetProperty pairing we saw above.
+If you know that all of a function's callers have checked that an optional argument has a value, either change the function to take the value directly or check the optional again in the local scope of the callee. For example:
+void g(int val) {
+ use(val);
+}
+
+void f(std::optional<int> opt) {
+ if (opt.has_value()) {
+ g(*opt);
+ }
+}
+and
+struct S {
+ std::optional<int> opt;
+ int x;
+};
+
+void g(const S &s) {
+ if (s.opt.has_value() && s.x > 10) {
+ use(*s.opt);
+}
+
+void f(S s) {
+ if (s.opt.has_value()) {
+ g(s);
+ }
+}
+using
declarationsThe check is aware of aliases of optional types that are created via using
declarations. For example:
using OptionalInt = std::optional<int>;
+
+void f(OptionalInt opt) {
+ use(opt.value()); // unsafe: it is unclear whether `opt` has a value.
+}
+The check does not currently report unsafe optional accesses in lambdas. A future version will expand the scope to lambdas, following the rules outlined above. It is best to follow the same principles when using optionals in lambdas.
+clang-tidy - cert-msc54-cpp
+ + +The cert-msc54-cpp check is an alias, please see bugprone-signal-handler for more information.
+clang-tidy - cppcoreguidelines-avoid-const-or-ref-data-members
+ +This check warns when structs or classes have const-qualified or reference (lvalue or rvalue) data members. Having such members is rarely useful, and makes the class only copy-constructible but not copy-assignable.
+Examples:
+// Bad, const-qualified member
+struct Const {
+ const int x;
+}
+
+// Good:
+class Foo {
+ public:
+ int get() const { return x; }
+ private:
+ int x;
+};
+
+// Bad, lvalue reference member
+struct Ref {
+ int& x;
+};
+
+// Good:
+struct Foo {
+ int* x;
+ std::unique_ptr<int> x;
+ std::shared_ptr<int> x;
+ gsl::not_null<int> x;
+};
+
+// Bad, rvalue reference member
+struct RefRef {
+ int&& x;
+};
+The check implements rule C.12 of C++ Core Guidelines.
+Further reading: Data members: Never const.
+clang-tidy - cppcoreguidelines-avoid-do-while
+ +Warns when using do-while
loops. They are less readable than plain while
loops, since the termination condition is at the end and the condition is not checked prior to the first iteration. This can lead to subtle bugs.
The check implements rule ES.75 of C++ Core Guidelines.
+Examples:
+int x;
+do {
+ std::cin >> x;
+ // ...
+} while (x < 0);
+IgnoreMacros
+Ignore the check when analyzing macros. This is useful for safely defining function-like macros:
+#define FOO_BAR(x) \
+do { \
+ foo(x); \
+ bar(x); \
+} while(0)
+Defaults to false.
+clang-tidy - cppcoreguidelines-macro-to-enum
+ + +The cppcoreguidelines-macro-to-enum check is an alias, please see modernize-macro-to-enum <../modernize/macro-to-enum>
for more information.
clang-tidy - misc-confusable-identifiers
+ +Warn about confusable identifiers, i.e. identifiers that are visually close to each other, but use different Unicode characters. This detects a potential attack described in CVE-2021-42574.
+Example:
+int fo; // Initial character is U+0066 (LATIN SMALL LETTER F).
+int fo; // Initial character is U+1D41F (MATHEMATICAL BOLD SMALL F) not U+0066 (LATIN SMALL LETTER F).
+clang-tidy - misc-const-correctness
+ +This check implements detection of local variables which could be declared as const
but are not. Declaring variables as const
is required or recommended by many coding guidelines, such as: CppCoreGuidelines ES.25 and AUTOSAR C++14 Rule A7-1-1 (6.7.1 Specifiers).
Please note that this check's analysis is type-based only. Variables that are not modified but used to create a non-const handle that might escape the scope are not diagnosed as potential const
.
// Declare a variable, which is not ``const`` ...
+int i = 42;
+// but use it as read-only. This means that `i` can be declared ``const``.
+int result = i * i; // Before transformation
+int const result = i * i; // After transformation
+The check can analyze values, pointers and references but not (yet) pointees:
+// Normal values like built-ins or objects.
+int potential_const_int = 42; // Before transformation
+int const potential_const_int = 42; // After transformation
+int copy_of_value = potential_const_int;
+
+MyClass could_be_const; // Before transformation
+MyClass const could_be_const; // After transformation
+could_be_const.const_qualified_method();
+
+// References can be declared const as well.
+int &reference_value = potential_const_int; // Before transformation
+int const& reference_value = potential_const_int; // After transformation
+int another_copy = reference_value;
+
+// The similar semantics of pointers are not (yet) analyzed.
+int *pointer_variable = &potential_const_int; // _NO_ 'const int *pointer_variable' suggestion.
+int last_copy = *pointer_variable;
+The automatic code transformation is only applied to variables that are declared in single declarations. You may want to prepare your code base with readability-isolate-declaration first.
+Note that there is the check cppcoreguidelines-avoid-non-const-global-variables to enforce const
correctness on all globals.
The check does not run on C code.
+The check will not analyze templated variables or variables that are instantiation dependent. Different instantiations can result in different const
correctness properties and in general it is not possible to find all instantiations of a template. The template might be used differently in an independent translation unit.
Pointees can not be analyzed for constness yet. The following code shows this limitation.
+// Declare a variable that will not be modified.
+int constant_value = 42;
+
+// Declare a pointer to that variable, that does not modify either, but misses 'const'.
+// Could be 'const int *pointer_to_constant = &constant_value;'
+int *pointer_to_constant = &constant_value;
+
+// Usage:
+int result = 520 * 120 * (*pointer_to_constant);
+This limitation affects the capability to add const
to methods which is not possible, too.
AnalyzeValues (default = true)
+Enable or disable the analysis of ordinary value variables, like int i = 42;
// Warning
+int i = 42;
+// No warning
+int const i = 42;
+
+// Warning
+int a[] = {42, 42, 42};
+// No warning
+int const a[] = {42, 42, 42};
+AnalyzeReferences (default = true)
+Enable or disable the analysis of reference variables, like int &ref = i;
int i = 42;
+// Warning
+int& ref = i;
+// No warning
+int const& ref = i;
+WarnPointersAsValues (default = false)
+This option enables the suggestion for const
of the pointer itself. Pointer values have two possibilities to be const
, the pointer and the value pointing to.
int value = 42;
+
+// Warning
+const int * pointer_variable = &value;
+// No warning
+const int *const pointer_variable = &value;
+TransformValues (default = true)
+Provides fixit-hints for value types that automatically add const
if its a single declaration.
// Before
+int value = 42;
+// After
+int const value = 42;
+
+// Before
+int a[] = {42, 42, 42};
+// After
+int const a[] = {42, 42, 42};
+
+// Result is modified later in its life-time. No diagnostic and fixit hint will be emitted.
+int result = value * 3;
+result -= 10;
+TransformReferences (default = true)
+Provides fixit-hints for reference types that automatically add const
if its a single declaration.
// This variable could still be a constant. But because there is a non-const reference to
+// it, it can not be transformed (yet).
+int value = 42;
+// The reference 'ref_value' is not modified and can be made 'const int &ref_value = value;'
+// Before
+int &ref_value = value;
+// After
+int const &ref_value = value;
+
+// Result is modified later in its life-time. No diagnostic and fixit hint will be emitted.
+int result = ref_value * 3;
+result -= 10;
+TransformPointersAsValues (default = false)
+Provides fixit-hints for pointers if their pointee is not changed. This does not analyze if the value-pointed-to is unchanged!
+Requires 'WarnPointersAsValues' to be 'true'.
+int value = 42;
+
+// Before
+const int * pointer_variable = &value;
+// After
+const int *const pointer_variable = &value;
+
+// Before
+const int * a[] = {&value, &value};
+// After
+const int *const a[] = {&value, &value};
+
+// Before
+int *ptr_value = &value;
+// After
+int *const ptr_value = &value;
+
+int result = 100 * (*ptr_value); // Does not modify the pointer itself.
+// This modification of the pointee is still allowed and not diagnosed.
+*ptr_value = 0;
+
+// The following pointer may not become a 'int *const'.
+int *changing_pointee = &value;
+changing_pointee = &result;
+clang-tidy - misc-use-anonymous-namespace
+ +Finds instances of static
functions or variables declared at global scope that could instead be moved into an anonymous namespace.
Anonymous namespaces are the "superior alternative" according to the C++ Standard. static
was proposed for deprecation, but later un-deprecated to keep C compatibility [1]. static
is an overloaded term with different meanings in different contexts, so it can create confusion.
The following uses of static
will not be diagnosed:
const
or constexpr
variables, since they already have implicit internal linkage in C++.Examples:
+// Bad
+static void foo();
+static int x;
+
+// Good
+namespace {
+ void foo();
+ int x;
+} // namespace
+HeaderFileExtensions
+A semicolon-separated list of filename extensions of header files (the filename extensions should not include "." prefix). Default is ";h;hh;hpp;hxx". For extension-less header files, using an empty string or leaving an empty string between ";" if there are other filename extensions.
+clang-tidy - modernize-macro-to-enum
+ +Replaces groups of adjacent macros with an unscoped anonymous enum. Using an unscoped anonymous enum ensures that everywhere the macro token was used previously, the enumerator name may be safely used.
+This check can be used to enforce the C++ core guideline Enum.1: Prefer enumerations over macros, within the constraints outlined below.
+Potential macros for replacement must meet the following constraints:
+-
, +
, ~
or !
, any of the binary operators ,
, -
, +
, *
, /
, %
, &
, |
, ^
, <
, >
, <=
, >=
, ==
, !=
, ||
, &&
, <<
, >>
or <=>
, the ternary operator ?:
and its GNU extension. Parenthesized expressions are also recognized. This recognizes most valid expressions. In particular, expressions with the sizeof
operator are not recognized.Each cluster of macros meeting the above constraints is presumed to be a set of values suitable for replacement by an anonymous enum. From there, a developer can give the anonymous enum a name and continue refactoring to a scoped enum if desired. Comments on the same line as a macro definition or between subsequent macro definitions are preserved in the output. No formatting is assumed in the provided replacements, although clang-tidy can optionally format all fixes.
+Warning
+Initializing expressions are assumed to be valid initializers for an enum. C requires that enum values fit into an int
, but this may not be the case for some accepted constant expressions. For instance 1 << 40
will not fit into an int
when the size of an int
is 32 bits.
Examples:
+#define RED 0xFF0000
+#define GREEN 0x00FF00
+#define BLUE 0x0000FF
+
+#define TM_NONE (-1) // No method selected.
+#define TM_ONE 1 // Use tailored method one.
+#define TM_TWO 2 // Use tailored method two. Method two
+ // is preferable to method one.
+#define TM_THREE 3 // Use tailored method three.
+becomes
+enum {
+RED = 0xFF0000,
+GREEN = 0x00FF00,
+BLUE = 0x0000FF
+};
+
+enum {
+TM_NONE = (-1), // No method selected.
+TM_ONE = 1, // Use tailored method one.
+TM_TWO = 2, // Use tailored method two. Method two
+ // is preferable to method one.
+TM_THREE = 3 // Use tailored method three.
+};
+clang-tidy - objc-nsdate-formatter
+ +When NSDateFormatter
is used to convert an NSDate
type to a String
type, the user can specify a custom format string. Certain format specifiers are undesirable despite being legal. See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns for all legal date patterns.
This checker reports as warnings the following string patterns in a date format specifier:
+clang-tidy - portability-std-allocator-const
+ +Report use of std::vector<const T>
(and similar containers of const elements). These are not allowed in standard C++, and should usually be std::vector<T>
instead."
Per C++ [allocator.requirements.general]
: "T is any cv-unqualified object type", std::allocator<const T>
is undefined. Many standard containers use std::allocator
by default and therefore their const T
instantiations are undefined.
libc++ defines std::allocator<const T>
as an extension which will be removed in the future.
libstdc++ and MSVC do not support std::allocator<const T>
:
// libstdc++ has a better diagnostic since https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48101
+std::deque<const int> deque; // error: static assertion failed: std::deque must have a non-const, non-volatile value_type
+std::set<const int> set; // error: static assertion failed: std::set must have a non-const, non-volatile value_type
+std::vector<int* const> vector; // error: static assertion failed: std::vector must have a non-const, non-volatile value_type
+
+// MSVC
+// error C2338: static_assert failed: 'The C++ Standard forbids containers of const elements because allocator<const T> is ill-formed.'
+Code bases only compiled with libc++ may accrue such undefined usage. This check finds such code and prevents backsliding while clean-up is ongoing.
+