DragonFly On-Line Manual Pages

Search: Section:  


EXTRACLANGTOOLS(1)             Extra Clang Tools            EXTRACLANGTOOLS(1)

NAME

extraclangtools - Extra Clang Tools Documentation Welcome to the clang-tools-extra project which contains extra tools built using Clang's tooling APIs. EXTRA CLANG TOOLS 8.0.0 RELEASE NOTES o Introduction o What's New in Extra Clang Tools 8.0.0? o Improvements to clangd o Improvements to clang-query o Improvements to clang-tidy Written by the LLVM Team Introduction This document contains the release notes for the Extra Clang Tools, part of the Clang release 8.0.0. Here we describe the status of the Extra Clang Tools in some detail, including major improvements from the previous release and new feature work. All LLVM releases may be downloaded from the LLVM releases web site. For more information about Clang or LLVM, including information about the latest release, please see the Clang Web Site or the LLVM Web Site. What's New in Extra Clang Tools 8.0.0? Some of the major new features and improvements to Extra Clang Tools are listed here. Generic improvements to Extra Clang Tools as a whole or to its underlying infrastructure are described first, followed by tool-specific sections. Improvements to clangd o clangd now adds namespace qualifiers in code completion, for example, if you type "vec", the list of completions will include "std::vector". See also: r343248. o When a global index is available, clangd will use it to augment the results of "go to definition" and "find references" queries. Global index also enables global code completion, which suggests symbols that are not imported in the current file and automatically inserts the missing #include directives. o clangd stores the symbol index on disk in a new compact binary serialization format. It is 10x more compact than YAML and 40% more compact than gzipped YAML. See also: r341375. o clangd has a new efficient symbol index suitable for complex and fuzzy queries and large code bases (e.g., LLVM, Chromium). This index is used for code completion, go to definition, and cross-references. The architecture of the index allows for complex and fuzzy retrieval criteria and sophisticated scoring. See also: discussion on the mailing list, design doc. o clangd has a new LSP extension that communicates information about activity on clangd's per-file worker thread. This information can be displayed to users to let them know that the language server is busy with something. For example, in clangd, building the AST blocks many other operations. More info: lsp-extension-file-status. o clangd has a new LSP extension that allows the client to supply the compilation commands over LSP, instead of finding compile_commands.json on disk. More info: lsp-extension-compilation-commands. o clangd has a new LSP extension that allows the client to request fixes to be sent together with diagnostics, instead of asynchronously. More info: lsp-extension-code-actions-in-diagnostics. o clangd has a new LSP extension that allows the client to resolve a symbol in a light-weight manner, without retrieving further information (like definition location, which may require consulting an index). More info: lsp-extension-symbol-info. Improvements to clang-query o A new command line parameter --preload was added to run commands from a file and then start the interactive interpreter. o The command q can was added as an alias for quit to exit the clang-query interpreter. o It is now possible to bind to named values (the result of let expressions). For example: let fn functionDecl() match fn.bind("foo") o It is now possible to write comments in clang-query code. This is primarily useful when using script-mode. Comments are all content following the # character on a line: # This is a comment match fn.bind("foo") # This is a trailing comment o The new set print-matcher true command now causes clang-query to print the evaluated matcher together with the resulting bindings. o A new output mode detailed-ast was added to clang-query. The existing dump output mode is now a deprecated alias for detailed-ast o Output modes can now be enabled or disabled non-exclusively. For example, # Enable detailed-ast without disabling other output, such as diag enable output detailed-ast m functionDecl() # Disable detailed-ast only disable output detailed-ast m functionDecl() Improvements to clang-tidy o New abseil-duration-comparison check. Checks for comparisons which should be done in the absl::Duration domain instead of the float of integer domains. o New abseil-duration-division check. Checks 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. o New abseil-duration-factory-float check. 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. o New abseil-duration-factory-scale check. Checks for cases where arguments to absl::Duration factory functions are scaled internally and could be changed to a different factory function. o New abseil-duration-subtraction check. Checks for cases where subtraction should be performed in the absl::Duration domain. o New abseil-faster-strsplit-delimiter check. Finds instances of absl::StrSplit() or absl::MaxSplits() where the delimiter is a single character string literal and replaces with a character. o New abseil-no-internal-dependencies check. Gives a warning if code using Abseil depends on internal details. o New abseil-no-namespace check. Ensures code does not open namespace absl as that violates Abseil's compatibility guidelines. o New abseil-redundant-strcat-calls check. Suggests removal of unnecessary calls to absl::StrCat when the result is being passed to another absl::StrCat or absl::StrAppend. o New abseil-str-cat-append check. Flags uses of absl::StrCat() to append to a std::string. Suggests absl::StrAppend() should be used instead. o New abseil-upgrade-duration-conversions check. Finds calls to absl::Duration arithmetic operators and factories whose argument needs an explicit cast to continue compiling after upcoming API changes. o New bugprone-too-small-loop-variable check. 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. o New cppcoreguidelines-macro-usage check. Finds macro usage that is considered problematic because better language constructs exist for the task. o New google-objc-function-naming check. Checks that function names in function declarations comply with the naming conventions described in the Google Objective-C Style Guide. o New misc-non-private-member-variables-in-classes check. Finds classes that not only contain the data (non-static member variables), but also have logic (non-static member functions), and diagnoses all member variables that have any other scope other than private. o New modernize-avoid-c-arrays check. Finds C-style array types and recommend to use std::array<> / std::vector<>. o New modernize-concat-nested-namespaces check. Checks for uses of nested namespaces in the form of namespace a { namespace b { ... }} and offers change to syntax introduced in C++17 standard: namespace a::b { ... }. o New modernize-deprecated-ios-base-aliases check. Detects usage of the deprecated member types of std::ios_base and replaces those that have a non-deprecated equivalent. o New modernize-use-nodiscard check. Adds [[nodiscard]] attributes (introduced in C++17) to member functions to highlight at compile time which return values should not be ignored. o New readability-const-return-type check. Checks for functions with a const-qualified return type and recommends removal of the const keyword. o New readability-isolate-decl check. Detects local variable declarations declaring more than one variable and tries to refactor the code to one statement per declaration. o New readability-magic-numbers check. Detects usage of magic numbers, numbers that are used as literals instead of introduced via constants or symbols. o New readability-redundant-preprocessor check. Finds potentially redundant preprocessor directives. o New readability-uppercase-literal-suffix check. Detects when the integral literal or floating point literal has non-uppercase suffix, and suggests to make the suffix uppercase. The list of destination suffixes can be optionally provided. o New alias cert-dcl16-c to readability-uppercase-literal-suffix added. o New alias cppcoreguidelines-avoid-c-arrays to modernize-avoid-c-arrays added. o New alias cppcoreguidelines-non-private-member-variables-in-classes to misc-non-private-member-variables-in-classes added. o New alias hicpp-avoid-c-arrays to modernize-avoid-c-arrays added. o New alias hicpp-uppercase-literal-suffix to readability-uppercase-literal-suffix added. o The cppcoreguidelines-narrowing-conversions check now detects more narrowing conversions: - integer to narrower signed integer (this is compiler implementation defined), - integer - floating point narrowing conversions, - floating point - integer narrowing conversions, - constants with narrowing conversions (even in ternary operator). o The objc-property-declaration check now ignores the Acronyms and IncludeDefaultAcronyms options. o The readability-redundant-smartptr-get check does not warn about calls inside macros anymore by default. o The readability-uppercase-literal-suffix check does not warn about literal suffixes inside macros anymore by default. CLANG-TIDY Contents o Clang-Tidy o Using clang-tidy o Suppressing Undesired Diagnostics See also: Clang-Tidy Checks 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: // 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) ... 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 for more information on arithmetic with absl::Duration. For example: 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: 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. 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: // 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); 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 arguements with a zero value and suggests using absl::ZeroDuration() instead. Examples: // 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(); 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: // 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 occurences 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. 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: // 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: 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 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: namespace absl { ... } will be prompted with a warning. See the full Abseil compatibility guidelines for more information. 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: 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 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. 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. 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. string s = "..."; if (s.find("Hello World") == 0) { /* do something */ } becomes string s = "..."; if (absl::StartsWith(s, "Hello World")) { /* do something */ } Options 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. IncludeStyle A string specifying which include-style is used, llvm or google. Default is llvm. AbseilStringsMatchHeader The location of Abseil's strings/match.h. Defaults to absl/strings/match.h. 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: std::atomic<int> a; absl::Duration d = absl::Milliseconds(a); d *= a; becomes 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. 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: accept(sockfd, addr, addrlen); // becomes accept4(sockfd, addr, addrlen, SOCK_CLOEXEC); 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: accept4(sockfd, addr, addrlen, SOCK_NONBLOCK); // becomes accept4(sockfd, addr, addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC); android-cloexec-creat The usage of creat() is not recommended, it's better to use open(). Examples: int fd = creat(path, mode); // becomes int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, mode); 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: int fd = dup(oldfd); // becomes int fd = fcntl(oldfd, F_DUPFD_CLOEXEC); 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: epoll_create(size); // becomes epoll_create1(EPOLL_CLOEXEC); 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: epoll_create1(0); // becomes epoll_create1(EPOLL_CLOEXEC); 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: fopen("fn", "r"); // becomes fopen("fn", "re"); android-cloexec-inotify-init The usage of inotify_init() is not recommended, it's better to use inotify_init1(). Examples: inotify_init(); // becomes inotify_init1(IN_CLOEXEC); 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: inotify_init1(IN_NONBLOCK); // becomes inotify_init1(IN_NONBLOCK | IN_CLOEXEC); 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: memfd_create(name, MFD_ALLOW_SEALING); // becomes memfd_create(name, MFD_ALLOW_SEALING | MFD_CLOEXEC); 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: 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); 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: socket(domain, type, SOCK_STREAM); // becomes socket(domain, type, SOCK_STREAM | SOCK_CLOEXEC); 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 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: 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: char cs[1]; while (TEMP_FAILURE_RETRY(read(STDIN_FILENO, cs, sizeof(cs))) != 0) { // Do something with cs. } 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. 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); 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. 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 StrictMode When zero (default value), the check will ignore leading and trailing underscores and case when comparing names - otherwise they are taken into account. 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 AssertMacros A comma-separated list of the names of assert macros to be checked. 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. bugprone-bool-pointer-implicit-conversion Checks for conditions based on implicit conversion from a bool pointer to bool. Example: bool *p; if (p) { // Never used in a pointer-specific way. } bugprone-copy-constructor-init Finds copy constructors where the constructor doesn't call the copy constructor of the base class. 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. class X4 : public Copyable { X4(const X4 &other) : Copyable() {} // other is missing }; The check also suggests a fix-its in some cases. bugprone-dangling-handle Detect dangling references in value handles like std::experimental::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: 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 HandleClasses A semicolon-separated list of class names that should be treated as handles. By default only std::experimental::basic_string_view is considered. 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 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 funcions which should not throw. Default value is an empty string. IgnoredExceptions Comma separated list containing type names which are not counted as thrown exceptions in the check. Default value is an empty string. bugprone-fold-init-type The check flags type mismatches in folds 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: o Truncation: The following code uses a floating point range and an int initial value, so trucation wil happen at every application of operator+ and the result will be 0, which might not be what the user expected. auto a = {0.5f, 0.5f, 0.5f, 0.5f}; return std::accumulate(std::begin(a), std::end(a), 0); o Overflow: The following code also returns 0. auto a = {65536LL * 65536 * 65536}; return std::accumulate(std::begin(a), std::end(a), 0); 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. 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. 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: 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. 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. 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. 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: o operands of operators expecting integral or bool types, o call expressions of integral or bool types, and o explicit cast expressions to integral or bool types, as these are interpreted as signs of deliberateness from the programmer. Examples: 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; 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: 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 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. bugprone-macro-repeated-side-effects Checks for repeated argument with side effects in macros. 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: 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 char *c = (char*) malloc(strlen(str) + 1); C++ example code: 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 char *c = new char[strlen(str) + 1]; Example for silencing the diagnostic: void bad_malloc(char *str) { char *c = (char*) malloc(strlen((str + 1))); } 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: 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: 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 CheckImplicitCasts is enabled the check also detects these cases, for instance: long f(int x) { return x * 1000; } Floating point Currently warnings are only written for integer conversion. No warning is written for this code: double f(float x) { return (double)(x * 10.0f); } Options CheckImplicitCasts If non-zero, enables detection of implicit casts. Default is non-zero. bugprone-move-forwarding-reference Warns if std::move is called on a forwarding reference, for example: template <typename T> void foo(T&& t) { bar(std::move(t)); } Forwarding references 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 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: 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. 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: #define INCREMENT_TWO(x, y) (x)++; (y)++ if (do_increment) INCREMENT_TWO(a, b); // (b)++ will be executed unconditionally. bugprone-parent-virtual-call Detects and fixes calls to grand-<?>parent virtual methods instead of calls to overridden parent's virtual methods. class A { int virtual foo() {...} }; class B: public A { int foo() override {...} }; class 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] }; 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: 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. 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. #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: 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. 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. 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. 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. 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*. 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 /. 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. 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. #define INT_SZ sizeof(int) int buf[] = { 42 }; void getInt(int* dst) { memcpy(dst, buf, sizeof(INT_SZ)); // sizeof(sizeof(int)) is suspicious. } Options WarnOnSizeOfConstant When non-zero, the check will warn on an expression like sizeof(CONSTANT). Default is 1. WarnOnSizeOfIntegerExpression When non-zero, the check will warn on an expression like sizeof(expr) where the expression results in an integer. Default is 0. WarnOnSizeOfThis When non-zero, the check will warn on an expression like sizeof(this). Default is 1. WarnOnSizeOfCompareToConstant When non-zero, 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 1. 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: 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: std::string("test", 200); // Will include random characters after "test". Creating an empty string from constructors with parameters is considered suspicious. The programmer should use the empty constructor instead. Examples: std::string("test", 0); // Creation of an empty string. Options WarnOnLargeLength When non-zero, the check will warn on a string with a length greater than LargeLengthThreshold. Default is 1. LargeLengthThreshold An integer specifying the large length threshold. Default is 0x800000. 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>: basic_string& operator=( CharT ch ); Numeric types can be implicitly casted to character types. std::string s; int x = 5965; s = 6; s = x; Use the appropriate conversion functions or character literals. std::string s; int x = 5965; s = '6'; s = std::to_string(x); In order to suppress false positives, use an explicit cast. std::string s; s = static_cast<char>(6); 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. 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. std::string str("abc\0def"); // "def" is truncated str += "\0"; // This statement is doing nothing if (str == "\0abc") return; // This expression is always true 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 StrictMode. We regard the enum as a (suspicious) bitmask if the three conditions below are true at the same time: o at most half of the elements of the enum are non pow-of-2 numbers (because of short enumerations) o there is another non pow-of-2 number than the enum constant representing all choices (the result "bitwise OR" operation of all enum elements) o 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: enum { A, B, C }; enum { D, E, F = 5 }; enum { G = 10, H = 11, I = 12 }; unsigned flag; flag = A | H; // OK, disjoint value intervalls 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 StrictMode Default value: 0. When non-null the suspicious bitmask usage will be investigated additionally to the different enum usage check. 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: 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 } 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: 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. 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: const char* SupportedFormat[] = { "Error %s", "Code " PRIu64, // May warn here. "Warning %s", }; Options SizeThreshold An unsigned integer specifying the minimum size of a string literal to be considered by the check. Default is 5U. RatioThreshold A string specifying the maximum threshold ratio [0, 1.0] of suspicious string literals to be considered. Default is ".2". MaxConcatenatedTokens An unsigned integer specifying the maximum number of concatenated tokens. Default is 5U. 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. 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. 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. 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: 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: while (readWhitespace()); Token t = readNextToken(); <?> or move the semicolon from the end of the first line to a new line: 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. 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. 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 < 0 when lower than, > 0 when greater than, == 0 when equals. A common mistake is to compare the result to 1 or -1. 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. if (strcmp(...) < 0.) // Incorrect usage of the returned value. Options WarnOnImplicitComparison When non-zero, the check will warn on implicit comparison. 1 by default. WarnOnLogicalNotComparison When non-zero, the check will warn on logical not comparison. 0 by default. 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. bugprone-swapped-arguments Finds potentially swapped arguments by looking at implicit conversions. 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. void f() { do { // some code continue; // terminating continue // some other code } while(false); 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: void f(int i) { if (i < 0) { // Exception is created but is not thrown. std::runtime_error("Unexpected argument"); } } 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. 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. 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. bugprone-undefined-memory-manipulation Finds calls of memory manipulation functions memset(), memcpy() and memmove() on not TriviallyCopyable objects resulting in undefined behavior. 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. bugprone-unused-raii Finds temporaries that look like RAII objects. The canonical example for this is a scoped lock. { 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: o Ignore code expanded from macros. Testing frameworks make heavy use of this. o Ignore types with trivial destructors. They are very unlikely to be RAII objects and there's no difference when they are deleted. o Ignore objects at the end of a compound statement (doesn't change behavior). o Ignore objects returned from a call. bugprone-unused-return-value Warns on unused function return values. The checked funtions can be configured. Options 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: o std::async(). Not using the return value makes the call synchronous. o 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. o 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. o 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(). o std::basic_string::empty() and std::vector::empty(). Not using the return value often indicates that the programmer confused the function with clear(). bugprone-use-after-move Warns if an object is used after it has been moved, for example: 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: messages.emplace_back(std::move(str)); str = "Greetings, stranger!\n"; std::cout << str; 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: if (condition) { messages.emplace_back(std::move(str)); } else { std::cout << str; } On the other hand, the following code does produce a warning: 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): 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. An erroneous warning can be silenced by reinitializing the object after the move: if (i == 1) { messages.emplace_back(std::move(str)); str = ""; } if (i == 2) { std::cout << str; } Subsections below explain more precisely what exactly the check considers to be a move, use, and reinitialization. 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: 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: 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. 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: o The variable occurs on the left-hand side of an assignment. o 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.) o 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. o reset() is called on the variable and the variable is of type std::unique_ptr, std::shared_ptr or std::weak_ptr. o 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: 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. bugprone-virtual-near-miss Warn if a function is a near miss (ie. the name is very similar and the function signiture is the same) to a virtual function from a base class. Example: 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? }; cert-dcl03-c The cert-dcl03-c check is an alias, please see misc-static-assert for more information. cert-dcl16-c The cert-dcl16-c check is an alias, please see readability-uppercase-literal-suffix for more information. 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. This check corresponds to the CERT C++ Coding Standard recommendation DCL21-CPP. Overloaded postfix increment and decrement operators should return a const object. 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. cert-dcl54-cpp The cert-dcl54-cpp check is an alias, please see misc-new-delete-overloads for more information. cert-dcl58-cpp Modification of the std or posix namespace can result in undefined behavior. This check warns for such modifications. Examples: 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. cert-dcl59-cpp The cert-dcl59-cpp check is an alias, please see google-build-namespaces for more information. 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(). cert-err09-cpp The cert-err09-cpp check is an alias, please see misc-throw-by-value-catch-by-reference for more information. 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. #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. 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(). 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. 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. cert-err61-cpp The cert-err61-cpp check is an alias, please see misc-throw-by-value-catch-by-reference for more information. cert-fio38-c The cert-fio38-c check is an alias, please see misc-non-copyable-objects for more information. 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. cert-msc30-c The cert-msc30-c check is an alias, please see cert-msc50-cpp for more information. cert-msc32-c The cert-msc32-c check is an alias, please see cert-msc51-cpp for more information. 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(). 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 and MSC32-C. Properly seed pseudorandom number generators. Examples: 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 DisallowedSeedTypes A comma-separated list of the type names which are disallowed. Default values are time_t, std::time_t. cert-oop11-cpp The cert-oop11-cpp check is an alias, please see performance-move-constructor-init for more information. cppcoreguidelines-avoid-c-arrays The cppcoreguidelines-avoid-c-arrays check is an alias, please see modernize-avoid-c-arrays for more information. 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 from the CppCoreGuidelines and 6.3.1 from High Integrity C++. For more information on why to avoid programming with goto you can read the famous paper A Case against the GO TO Statement.. The check diagnoses goto for backward jumps in every language mode. These should be replaced with C/C++ looping constructs. // 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. 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++. cppcoreguidelines-avoid-magic-numbers The cppcoreguidelines-avoid-magic-numbers check is an alias, please see readability-magic-numbers for more information. cppcoreguidelines-c-copy-assignment-signature The cppcoreguidelines-c-copy-assignment-signature check is an alias, please see misc-unconventional-assign-operator for more information. 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. 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, ES.30, ES.31 and ES.33. Options AllowedRegexp A regular expression to filter allowed macros. For example DEBUG*|LIBTORRENT*|TORRENT*|UNI* could be applied to filter libtorrent. Default value is ^DEBUG_*. 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 0/false. IgnoreCommandLineMacros Boolean flag to toggle ignoring command-line-defined macros. Default value is 1/true. 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: o an integer to a narrower integer (e.g. char to unsigned char), o an integer to a narrower floating-point (e.g. uint64_t to float), o a floating-point to an integer (e.g. double to int), o a floating-point to a narrower floating-point (e.g. double to float) if WarnOnFloatingPointNarrowingConversion Option is set. This check will flag: o 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);, o All applications of binary operators with a narrowing conversions. For example: int i; i+= 0.1;. Options WarnOnFloatingPointNarrowingConversion When non-zero, the check will warn on narrowing floating point conversion (e.g. double to float). 1 by default. PedanticMode When non-zero, 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;). 0 by default. FAQ o 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]. o 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. 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. There is no attempt made to provide fix-it hints, since manual resource management isn't easily transformed automatically into RAII. // 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 Allocations Semicolon-separated list of fully qualified names of memory allocation functions. Defaults to ::malloc;::calloc. Deallocations Semicolon-separated list of fully qualified names of memory allocation functions. Defaults to ::free. Reallocations Semicolon-separated list of fully qualified names of memory allocation functions. Defaults to ::realloc. 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 for more information. 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 are I.11, C.33, R.3 and GSL.Views The definition of a gsl::owner<T*> is straight forward 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. 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. // 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. // 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 correclty 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. 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 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. 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. 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: o std::exchange o std::vector<gsl::owner<T*>> // 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: // 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 catched 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. 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. 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 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". IncludeStyle A string specifying which include-style is used, llvm or google. Default is llvm. 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. 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. 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. 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 IgnoreArrays If set to non-zero, 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 0. 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. 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. 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. 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. 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. 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: 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 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 AllowSoleDefaultDtor When set to 1 (default is 0), this check doesn't flag classes with a sole, explicitly defaulted destructor. An example for such a class is: struct A { virtual ~A() = default; }; AllowMissingMoveFunctions When set to 1 (default is 0), 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: struct A { A(const A&); A& operator=(const A&); ~A(); } fuchsia-default-arguments Warns if a function or method is declared or called with default arguments. For example, the declaration: int foo(int value = 5) { return value; } will cause a warning. A function call expression that uses a default argument will be diagnosed. Calling it without defaults will not cause a warning: foo(); // warning foo(0); // no warning See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md fuchsia-header-anon-namespaces The fuchsia-header-anon-namespaces check is an alias, please see google-build-namespace for more information. 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: 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: 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 fuchsia-overloaded-operator Warns if an operator is overloaded, except for the assignment (copy and move) operators. For example: 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 fuchsia-restrict-system-includes Checks for allowed system includes and suggests removal of any others. It is important to note that running this check with fixes may break code, as the fix removes headers. Fixes are applied to source and header files, but not to system headers. For example, given the allowed system includes `a.h,b*': #include <a.h> #include <b.h> #include <bar.h> #include <c.h> // Warning, as c.h is not explicitly allowed All system includes can be allowed with `*', and all can be disallowed with an empty string (`'). Options 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. 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: 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 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: // 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: // 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 fuchsia-virtual-inheritance Warns if classes are defined with virtual inheritance. For example, classes should not be defined with virtual inheritance: class B : public virtual A {}; // warning See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md 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. 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 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). google-build-using-namespace Finds using namespace directives. The check implements the following rule of the Google C++ Style Guide: You may not use a using-directive to make all names from a namespace available. // Forbidden -- This pollutes the namespace. using namespace foo; Corresponding cpplint.py check name: build/namespaces. google-default-arguments Checks that default arguments are not given for virtual methods. See https://google.github.io/styleguide/cppguide.html#Default_Arguments 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: 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: struct S { S(int a); explicit S(const S&); operator bool() const; ... will become struct S { explicit S(int a); S(const S&); explicit operator bool() const; ... See https://google.github.io/styleguide/cppguide.html#Explicit_Constructors 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 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). 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: - (void)readFile { if ([self isError]) { @throw [NSException exceptionWithName:...]; } } Instead, returning an error via NSError ** is preferred: - (BOOL)readFileWithError:(NSError **)error { if ([self isError]) { *error = [NSError errorWithDomain:...]; return NO; } return YES; } The corresponding style guide rule: http://google.github.io/styleguide/objcguide.html#avoid-throwing-exceptions 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: 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: static bool IsPositive(int i) { return i > 0; } bool *ABCIsNegative(int i) { return i < 0; } 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: http://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: static NSString* myString = @"hello"; The fix will be: static NSString* gMyString = @"hello"; Another example of constant: static NSString* const myConstString = @"hello"; The fix will be: static NSString* const kMyConstString = @"hello"; However for code that prefixed with non-alphabetical characters like: static NSString* __anotherString = @"world"; The check will give a warning message but will not be able to suggest a fix. The user need to fix it on his own. google-readability-braces-around-statements The google-readability-braces-around-statements check is an alias, please see readability-braces-around-statements for more information. 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. google-readability-function-size The google-readability-function-size check is an alias, please see readability-function-size for more information. google-readability-namespace-comments The google-readability-namespace-comments check is an alias, please see llvm-namespace-comment for more information. 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 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. Correspondig cpplint.py check: runtime/int. Options UnsignedTypePrefix A string specifying the unsigned type prefix. Default is uint. SignedTypePrefix A string specifying the signed type prefix. Default is int. TypeSuffix A string specifying the type suffix. Default is an empty string. google-runtime-operator Finds overloads of unary operator &. https://google.github.io/styleguide/cppguide.html#Operator_Overloading Corresponding cpplint.py check name: runtime/operator. google-runtime-references Checks the usage of non-constant references in function parameters. The corresponding style guide rule: https://google.github.io/styleguide/cppguide.html#Reference_Arguments Options WhiteListTypes A semicolon-separated list of names of whitelist types. Default is empty. hicpp-avoid-c-arrays The hicpp-avoid-c-arrays check is an alias, please see modernize-avoid-c-arrays for more information. hicpp-avoid-goto 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. hicpp-braces-around-statements The hicpp-braces-around-statements check is an alias, please see readability-braces-around-statements for more information. It enforces the rule 6.1.1. hicpp-deprecated-headers The hicpp-deprecated-headers check is an alias, please see modernize-deprecated-headers for more information. It enforces the rule 1.3.3. hicpp-exception-baseclass Ensure that every value that in a throw expression is an instance of std::exception. This enforces rule 15.1 of the High Integrity C++ Coding Standard. 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(); } hicpp-explicit-conversions This check is an alias for google-explicit-constructor. Used to enforce parts of rule 5.4.1. 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: o cppcoreguidelines-pro-type-static-cast-downcast o cppcoreguidelines-pro-type-reinterpret-cast o cppcoreguidelines-pro-type-const-cast o cppcoreguidelines-pro-type-cstyle-cast hicpp-function-size This check is an alias for readability-function-size. Useful to enforce multiple sections on function complexity. o rule 8.2.2 o rule 8.3.1 o rule 8.3.2 hicpp-invalid-access-moved This check is an alias for bugprone-use-after-move. Implements parts of the rule 8.4.1 to check if moved-from objects are accessed. hicpp-member-init This check is an alias for cppcoreguidelines-pro-type-member-init. Implements the check for rule 12.4.2 to initialize class members in the right order. hicpp-move-const-arg The hicpp-move-const-arg check is an alias, please see performance-move-const-arg for more information. It enforces the rule 17.3.1. 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 and rule 6.1.4 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. void f1() { int i = determineTheNumber(); if(i > 0) { // Some Calculation EXTRACLANGTOOLS(1) Extra Clang Tools EXTRACLANGTOOLS(1)

NAME

extraclangtools - Extra Clang Tools Documentation Welcome to the clang-tools-extra project which contains extra tools built using Clang's tooling APIs. EXTRA CLANG TOOLS 8.0.0 RELEASE NOTES o Introduction o What's New in Extra Clang Tools 8.0.0? o Improvements to clangd o Improvements to clang-query o Improvements to clang-tidy Written by the LLVM Team Introduction This document contains the release notes for the Extra Clang Tools, part of the Clang release 8.0.0. Here we describe the status of the Extra Clang Tools in some detail, including major improvements from the previous release and new feature work. All LLVM releases may be downloaded from the LLVM releases web site. For more information about Clang or LLVM, including information about the latest release, please see the Clang Web Site or the LLVM Web Site. What's New in Extra Clang Tools 8.0.0? Some of the major new features and improvements to Extra Clang Tools are listed here. Generic improvements to Extra Clang Tools as a whole or to its underlying infrastructure are described first, followed by tool-specific sections. Improvements to clangd o clangd now adds namespace qualifiers in code completion, for example, if you type "vec", the list of completions will include "std::vector". See also: r343248. o When a global index is available, clangd will use it to augment the results of "go to definition" and "find references" queries. Global index also enables global code completion, which suggests symbols that are not imported in the current file and automatically inserts the missing #include directives. o clangd stores the symbol index on disk in a new compact binary serialization format. It is 10x more compact than YAML and 40% more compact than gzipped YAML. See also: r341375. o clangd has a new efficient symbol index suitable for complex and fuzzy queries and large code bases (e.g., LLVM, Chromium). This index is used for code completion, go to definition, and cross-references. The architecture of the index allows for complex and fuzzy retrieval criteria and sophisticated scoring. See also: discussion on the mailing list, design doc. o clangd has a new LSP extension that communicates information about activity on clangd's per-file worker thread. This information can be displayed to users to let them know that the language server is busy with something. For example, in clangd, building the AST blocks many other operations. More info: lsp-extension-file-status. o clangd has a new LSP extension that allows the client to supply the compilation commands over LSP, instead of finding compile_commands.json on disk. More info: lsp-extension-compilation-commands. o clangd has a new LSP extension that allows the client to request fixes to be sent together with diagnostics, instead of asynchronously. More info: lsp-extension-code-actions-in-diagnostics. o clangd has a new LSP extension that allows the client to resolve a symbol in a light-weight manner, without retrieving further information (like definition location, which may require consulting an index). More info: lsp-extension-symbol-info. Improvements to clang-query o A new command line parameter --preload was added to run commands from a file and then start the interactive interpreter. o The command q can was added as an alias for quit to exit the clang-query interpreter. o It is now possible to bind to named values (the result of let expressions). For example: let fn functionDecl() match fn.bind("foo") o It is now possible to write comments in clang-query code. This is primarily useful when using script-mode. Comments are all content following the # character on a line: # This is a comment match fn.bind("foo") # This is a trailing comment o The new set print-matcher true command now causes clang-query to print the evaluated matcher together with the resulting bindings. o A new output mode detailed-ast was added to clang-query. The existing dump output mode is now a deprecated alias for detailed-ast o Output modes can now be enabled or disabled non-exclusively. For example, # Enable detailed-ast without disabling other output, such as diag enable output detailed-ast m functionDecl() # Disable detailed-ast only disable output detailed-ast m functionDecl() Improvements to clang-tidy o New abseil-duration-comparison check. Checks for comparisons which should be done in the absl::Duration domain instead of the float of integer domains. o New abseil-duration-division check. Checks 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. o New abseil-duration-factory-float check. 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. o New abseil-duration-factory-scale check. Checks for cases where arguments to absl::Duration factory functions are scaled internally and could be changed to a different factory function. o New abseil-duration-subtraction check. Checks for cases where subtraction should be performed in the absl::Duration domain. o New abseil-faster-strsplit-delimiter check. Finds instances of absl::StrSplit() or absl::MaxSplits() where the delimiter is a single character string literal and replaces with a character. o New abseil-no-internal-dependencies check. Gives a warning if code using Abseil depends on internal details. o New abseil-no-namespace check. Ensures code does not open namespace absl as that violates Abseil's compatibility guidelines. o New abseil-redundant-strcat-calls check. Suggests removal of unnecessary calls to absl::StrCat when the result is being passed to another absl::StrCat or absl::StrAppend. o New abseil-str-cat-append check. Flags uses of absl::StrCat() to append to a std::string. Suggests absl::StrAppend() should be used instead. o New abseil-upgrade-duration-conversions check. Finds calls to absl::Duration arithmetic operators and factories whose argument needs an explicit cast to continue compiling after upcoming API changes. o New bugprone-too-small-loop-variable check. 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. o New cppcoreguidelines-macro-usage check. Finds macro usage that is considered problematic because better language constructs exist for the task. o New google-objc-function-naming check. Checks that function names in function declarations comply with the naming conventions described in the Google Objective-C Style Guide. o New misc-non-private-member-variables-in-classes check. Finds classes that not only contain the data (non-static member variables), but also have logic (non-static member functions), and diagnoses all member variables that have any other scope other than private. o New modernize-avoid-c-arrays check. Finds C-style array types and recommend to use std::array<> / std::vector<>. o New modernize-concat-nested-namespaces check. Checks for uses of nested namespaces in the form of namespace a { namespace b { ... }} and offers change to syntax introduced in C++17 standard: namespace a::b { ... }. o New modernize-deprecated-ios-base-aliases check. Detects usage of the deprecated member types of std::ios_base and replaces those that have a non-deprecated equivalent. o New modernize-use-nodiscard check. Adds [[nodiscard]] attributes (introduced in C++17) to member functions to highlight at compile time which return values should not be ignored. o New readability-const-return-type check. Checks for functions with a const-qualified return type and recommends removal of the const keyword. o New readability-isolate-decl check. Detects local variable declarations declaring more than one variable and tries to refactor the code to one statement per declaration. o New readability-magic-numbers check. Detects usage of magic numbers, numbers that are used as literals instead of introduced via constants or symbols. o New readability-redundant-preprocessor check. Finds potentially redundant preprocessor directives. o New readability-uppercase-literal-suffix check. Detects when the integral literal or floating point literal has non-uppercase suffix, and suggests to make the suffix uppercase. The list of destination suffixes can be optionally provided. o New alias cert-dcl16-c to readability-uppercase-literal-suffix added. o New alias cppcoreguidelines-avoid-c-arrays to modernize-avoid-c-arrays added. o New alias cppcoreguidelines-non-private-member-variables-in-classes to misc-non-private-member-variables-in-classes added. o New alias hicpp-avoid-c-arrays to modernize-avoid-c-arrays added. o New alias hicpp-uppercase-literal-suffix to readability-uppercase-literal-suffix added. o The cppcoreguidelines-narrowing-conversions check now detects more narrowing conversions: - integer to narrower signed integer (this is compiler implementation defined), - integer - floating point narrowing conversions, - floating point - integer narrowing conversions, - constants with narrowing conversions (even in ternary operator). o The objc-property-declaration check now ignores the Acronyms and IncludeDefaultAcronyms options. o The readability-redundant-smartptr-get check does not warn about calls inside macros anymore by default. o The readability-uppercase-literal-suffix check does not warn about literal suffixes inside macros anymore by default. CLANG-TIDY Contents o Clang-Tidy o Using clang-tidy o Suppressing Undesired Diagnostics See also: Clang-Tidy Checks 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: // 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) ... 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 for more information on arithmetic with absl::Duration. For example: 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: 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. 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: // 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); 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 arguements with a zero value and suggests using absl::ZeroDuration() instead. Examples: // 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(); 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: // 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 occurences 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. 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: // 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: 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 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: namespace absl { ... } will be prompted with a warning. See the full Abseil compatibility guidelines for more information. 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: 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 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. 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. 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. string s = "..."; if (s.find("Hello World") == 0) { /* do something */ } becomes string s = "..."; if (absl::StartsWith(s, "Hello World")) { /* do something */ } Options 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. IncludeStyle A string specifying which include-style is used, llvm or google. Default is llvm. AbseilStringsMatchHeader The location of Abseil's strings/match.h. Defaults to absl/strings/match.h. 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: std::atomic<int> a; absl::Duration d = absl::Milliseconds(a); d *= a; becomes 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. 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: accept(sockfd, addr, addrlen); // becomes accept4(sockfd, addr, addrlen, SOCK_CLOEXEC); 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: accept4(sockfd, addr, addrlen, SOCK_NONBLOCK); // becomes accept4(sockfd, addr, addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC); android-cloexec-creat The usage of creat() is not recommended, it's better to use open(). Examples: int fd = creat(path, mode); // becomes int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, mode); 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: int fd = dup(oldfd); // becomes int fd = fcntl(oldfd, F_DUPFD_CLOEXEC); 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: epoll_create(size); // becomes epoll_create1(EPOLL_CLOEXEC); 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: epoll_create1(0); // becomes epoll_create1(EPOLL_CLOEXEC); 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: fopen("fn", "r"); // becomes fopen("fn", "re"); android-cloexec-inotify-init The usage of inotify_init() is not recommended, it's better to use inotify_init1(). Examples: inotify_init(); // becomes inotify_init1(IN_CLOEXEC); 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: inotify_init1(IN_NONBLOCK); // becomes inotify_init1(IN_NONBLOCK | IN_CLOEXEC); 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: memfd_create(name, MFD_ALLOW_SEALING); // becomes memfd_create(name, MFD_ALLOW_SEALING | MFD_CLOEXEC); 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: 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); 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: socket(domain, type, SOCK_STREAM); // becomes socket(domain, type, SOCK_STREAM | SOCK_CLOEXEC); 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 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: 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: char cs[1]; while (TEMP_FAILURE_RETRY(read(STDIN_FILENO, cs, sizeof(cs))) != 0) { // Do something with cs. } 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. 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); 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. 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 StrictMode When zero (default value), the check will ignore leading and trailing underscores and case when comparing names - otherwise they are taken into account. 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 AssertMacros A comma-separated list of the names of assert macros to be checked. 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. bugprone-bool-pointer-implicit-conversion Checks for conditions based on implicit conversion from a bool pointer to bool. Example: bool *p; if (p) { // Never used in a pointer-specific way. } bugprone-copy-constructor-init Finds copy constructors where the constructor doesn't call the copy constructor of the base class. 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. class X4 : public Copyable { X4(const X4 &other) : Copyable() {} // other is missing }; The check also suggests a fix-its in some cases. bugprone-dangling-handle Detect dangling references in value handles like std::experimental::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: 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 HandleClasses A semicolon-separated list of class names that should be treated as handles. By default only std::experimental::basic_string_view is considered. 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 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 funcions which should not throw. Default value is an empty string. IgnoredExceptions Comma separated list containing type names which are not counted as thrown exceptions in the check. Default value is an empty string. bugprone-fold-init-type The check flags type mismatches in folds 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: o Truncation: The following code uses a floating point range and an int initial value, so trucation wil happen at every application of operator+ and the result will be 0, which might not be what the user expected. auto a = {0.5f, 0.5f, 0.5f, 0.5f}; return std::accumulate(std::begin(a), std::end(a), 0); o Overflow: The following code also returns 0. auto a = {65536LL * 65536 * 65536}; return std::accumulate(std::begin(a), std::end(a), 0); 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. 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. 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: 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. 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. 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. 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: o operands of operators expecting integral or bool types, o call expressions of integral or bool types, and o explicit cast expressions to integral or bool types, as these are interpreted as signs of deliberateness from the programmer. Examples: 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; 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: 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 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. bugprone-macro-repeated-side-effects Checks for repeated argument with side effects in macros. 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: 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 char *c = (char*) malloc(strlen(str) + 1); C++ example code: 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 char *c = new char[strlen(str) + 1]; Example for silencing the diagnostic: void bad_malloc(char *str) { char *c = (char*) malloc(strlen((str + 1))); } 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: 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: 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 CheckImplicitCasts is enabled the check also detects these cases, for instance: long f(int x) { return x * 1000; } Floating point Currently warnings are only written for integer conversion. No warning is written for this code: double f(float x) { return (double)(x * 10.0f); } Options CheckImplicitCasts If non-zero, enables detection of implicit casts. Default is non-zero. bugprone-move-forwarding-reference Warns if std::move is called on a forwarding reference, for example: template <typename T> void foo(T&& t) { bar(std::move(t)); } Forwarding references 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 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: 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. 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: #define INCREMENT_TWO(x, y) (x)++; (y)++ if (do_increment) INCREMENT_TWO(a, b); // (b)++ will be executed unconditionally. bugprone-parent-virtual-call Detects and fixes calls to grand-<?>parent virtual methods instead of calls to overridden parent's virtual methods. class A { int virtual foo() {...} }; class B: public A { int foo() override {...} }; class 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] }; 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: 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. 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. #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: 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. 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. 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. 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. 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*. 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 /. 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. 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. #define INT_SZ sizeof(int) int buf[] = { 42 }; void getInt(int* dst) { memcpy(dst, buf, sizeof(INT_SZ)); // sizeof(sizeof(int)) is suspicious. } Options WarnOnSizeOfConstant When non-zero, the check will warn on an expression like sizeof(CONSTANT). Default is 1. WarnOnSizeOfIntegerExpression When non-zero, the check will warn on an expression like sizeof(expr) where the expression results in an integer. Default is 0. WarnOnSizeOfThis When non-zero, the check will warn on an expression like sizeof(this). Default is 1. WarnOnSizeOfCompareToConstant When non-zero, 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 1. 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: 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: std::string("test", 200); // Will include random characters after "test". Creating an empty string from constructors with parameters is considered suspicious. The programmer should use the empty constructor instead. Examples: std::string("test", 0); // Creation of an empty string. Options WarnOnLargeLength When non-zero, the check will warn on a string with a length greater than LargeLengthThreshold. Default is 1. LargeLengthThreshold An integer specifying the large length threshold. Default is 0x800000. 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>: basic_string& operator=( CharT ch ); Numeric types can be implicitly casted to character types. std::string s; int x = 5965; s = 6; s = x; Use the appropriate conversion functions or character literals. std::string s; int x = 5965; s = '6'; s = std::to_string(x); In order to suppress false positives, use an explicit cast. std::string s; s = static_cast<char>(6); 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. 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. std::string str("abc\0def"); // "def" is truncated str += "\0"; // This statement is doing nothing if (str == "\0abc") return; // This expression is always true 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 StrictMode. We regard the enum as a (suspicious) bitmask if the three conditions below are true at the same time: o at most half of the elements of the enum are non pow-of-2 numbers (because of short enumerations) o there is another non pow-of-2 number than the enum constant representing all choices (the result "bitwise OR" operation of all enum elements) o 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: enum { A, B, C }; enum { D, E, F = 5 }; enum { G = 10, H = 11, I = 12 }; unsigned flag; flag = A | H; // OK, disjoint value intervalls 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 StrictMode Default value: 0. When non-null the suspicious bitmask usage will be investigated additionally to the different enum usage check. 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: 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 } 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: 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. 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: const char* SupportedFormat[] = { "Error %s", "Code " PRIu64, // May warn here. "Warning %s", }; Options SizeThreshold An unsigned integer specifying the minimum size of a string literal to be considered by the check. Default is 5U. RatioThreshold A string specifying the maximum threshold ratio [0, 1.0] of suspicious string literals to be considered. Default is ".2". MaxConcatenatedTokens An unsigned integer specifying the maximum number of concatenated tokens. Default is 5U. 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. 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. 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. 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: 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: while (readWhitespace()); Token t = readNextToken(); <?> or move the semicolon from the end of the first line to a new line: 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. 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. 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 < 0 when lower than, > 0 when greater than, == 0 when equals. A common mistake is to compare the result to 1 or -1. 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. if (strcmp(...) < 0.) // Incorrect usage of the returned value. Options WarnOnImplicitComparison When non-zero, the check will warn on implicit comparison. 1 by default. WarnOnLogicalNotComparison When non-zero, the check will warn on logical not comparison. 0 by default. 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. bugprone-swapped-arguments Finds potentially swapped arguments by looking at implicit conversions. 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. void f() { do { // some code continue; // terminating continue // some other code } while(false); 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: void f(int i) { if (i < 0) { // Exception is created but is not thrown. std::runtime_error("Unexpected argument"); } } 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. 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. 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. bugprone-undefined-memory-manipulation Finds calls of memory manipulation functions memset(), memcpy() and memmove() on not TriviallyCopyable objects resulting in undefined behavior. 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. bugprone-unused-raii Finds temporaries that look like RAII objects. The canonical example for this is a scoped lock. { 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: o Ignore code expanded from macros. Testing frameworks make heavy use of this. o Ignore types with trivial destructors. They are very unlikely to be RAII objects and there's no difference when they are deleted. o Ignore objects at the end of a compound statement (doesn't change behavior). o Ignore objects returned from a call. bugprone-unused-return-value Warns on unused function return values. The checked funtions can be configured. Options 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: o std::async(). Not using the return value makes the call synchronous. o 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. o 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. o 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(). o std::basic_string::empty() and std::vector::empty(). Not using the return value often indicates that the programmer confused the function with clear(). bugprone-use-after-move Warns if an object is used after it has been moved, for example: 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: messages.emplace_back(std::move(str)); str = "Greetings, stranger!\n"; std::cout << str; 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: if (condition) { messages.emplace_back(std::move(str)); } else { std::cout << str; } On the other hand, the following code does produce a warning: 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): 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. An erroneous warning can be silenced by reinitializing the object after the move: if (i == 1) { messages.emplace_back(std::move(str)); str = ""; } if (i == 2) { std::cout << str; } Subsections below explain more precisely what exactly the check considers to be a move, use, and reinitialization. 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: 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: 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. 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: o The variable occurs on the left-hand side of an assignment. o 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.) o 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. o reset() is called on the variable and the variable is of type std::unique_ptr, std::shared_ptr or std::weak_ptr. o 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: 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. bugprone-virtual-near-miss Warn if a function is a near miss (ie. the name is very similar and the function signiture is the same) to a virtual function from a base class. Example: 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? }; cert-dcl03-c The cert-dcl03-c check is an alias, please see misc-static-assert for more information. cert-dcl16-c The cert-dcl16-c check is an alias, please see readability-uppercase-literal-suffix for more information. 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. This check corresponds to the CERT C++ Coding Standard recommendation DCL21-CPP. Overloaded postfix increment and decrement operators should return a const object. 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. cert-dcl54-cpp The cert-dcl54-cpp check is an alias, please see misc-new-delete-overloads for more information. cert-dcl58-cpp Modification of the std or posix namespace can result in undefined behavior. This check warns for such modifications. Examples: 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. cert-dcl59-cpp The cert-dcl59-cpp check is an alias, please see google-build-namespaces for more information. 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(). cert-err09-cpp The cert-err09-cpp check is an alias, please see misc-throw-by-value-catch-by-reference for more information. 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. #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. 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(). 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. 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. cert-err61-cpp The cert-err61-cpp check is an alias, please see misc-throw-by-value-catch-by-reference for more information. cert-fio38-c The cert-fio38-c check is an alias, please see misc-non-copyable-objects for more information. 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. cert-msc30-c The cert-msc30-c check is an alias, please see cert-msc50-cpp for more information. cert-msc32-c The cert-msc32-c check is an alias, please see cert-msc51-cpp for more information. 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(). 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 and MSC32-C. Properly seed pseudorandom number generators. Examples: 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 DisallowedSeedTypes A comma-separated list of the type names which are disallowed. Default values are time_t, std::time_t. cert-oop11-cpp The cert-oop11-cpp check is an alias, please see performance-move-constructor-init for more information. cppcoreguidelines-avoid-c-arrays The cppcoreguidelines-avoid-c-arrays check is an alias, please see modernize-avoid-c-arrays for more information. 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 from the CppCoreGuidelines and 6.3.1 from High Integrity C++. For more information on why to avoid programming with goto you can read the famous paper A Case against the GO TO Statement.. The check diagnoses goto for backward jumps in every language mode. These should be replaced with C/C++ looping constructs. // 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. 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++. cppcoreguidelines-avoid-magic-numbers The cppcoreguidelines-avoid-magic-numbers check is an alias, please see readability-magic-numbers for more information. cppcoreguidelines-c-copy-assignment-signature The cppcoreguidelines-c-copy-assignment-signature check is an alias, please see misc-unconventional-assign-operator for more information. 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. 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, ES.30, ES.31 and ES.33. Options AllowedRegexp A regular expression to filter allowed macros. For example DEBUG*|LIBTORRENT*|TORRENT*|UNI* could be applied to filter libtorrent. Default value is ^DEBUG_*. 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 0/false. IgnoreCommandLineMacros Boolean flag to toggle ignoring command-line-defined macros. Default value is 1/true. 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: o an integer to a narrower integer (e.g. char to unsigned char), o an integer to a narrower floating-point (e.g. uint64_t to float), o a floating-point to an integer (e.g. double to int), o a floating-point to a narrower floating-point (e.g. double to float) if WarnOnFloatingPointNarrowingConversion Option is set. This check will flag: o 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);, o All applications of binary operators with a narrowing conversions. For example: int i; i+= 0.1;. Options WarnOnFloatingPointNarrowingConversion When non-zero, the check will warn on narrowing floating point conversion (e.g. double to float). 1 by default. PedanticMode When non-zero, 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;). 0 by default. FAQ o 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]. o 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. 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. There is no attempt made to provide fix-it hints, since manual resource management isn't easily transformed automatically into RAII. // 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 Allocations Semicolon-separated list of fully qualified names of memory allocation functions. Defaults to ::malloc;::calloc. Deallocations Semicolon-separated list of fully qualified names of memory allocation functions. Defaults to ::free. Reallocations Semicolon-separated list of fully qualified names of memory allocation functions. Defaults to ::realloc. 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 for more information. 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 are I.11, C.33, R.3 and GSL.Views The definition of a gsl::owner<T*> is straight forward 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. 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. // 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. // 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 correclty 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. 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 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. 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. 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: o std::exchange o std::vector<gsl::owner<T*>> // 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: // 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 catched 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. 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. 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 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". IncludeStyle A string specifying which include-style is used, llvm or google. Default is llvm. 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. 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. 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. 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 IgnoreArrays If set to non-zero, 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 0. 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. 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. 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. 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. 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. 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: 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 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 AllowSoleDefaultDtor When set to 1 (default is 0), this check doesn't flag classes with a sole, explicitly defaulted destructor. An example for such a class is: struct A { virtual ~A() = default; }; AllowMissingMoveFunctions When set to 1 (default is 0), 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: struct A { A(const A&); A& operator=(const A&); ~A(); } fuchsia-default-arguments Warns if a function or method is declared or called with default arguments. For example, the declaration: int foo(int value = 5) { return value; } will cause a warning. A function call expression that uses a default argument will be diagnosed. Calling it without defaults will not cause a warning: foo(); // warning foo(0); // no warning See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md fuchsia-header-anon-namespaces The fuchsia-header-anon-namespaces check is an alias, please see google-build-namespace for more information. 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: 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: 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 fuchsia-overloaded-operator Warns if an operator is overloaded, except for the assignment (copy and move) operators. For example: 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 fuchsia-restrict-system-includes Checks for allowed system includes and suggests removal of any others. It is important to note that running this check with fixes may break code, as the fix removes headers. Fixes are applied to source and header files, but not to system headers. For example, given the allowed system includes `a.h,b*': #include <a.h> #include <b.h> #include <bar.h> #include <c.h> // Warning, as c.h is not explicitly allowed All system includes can be allowed with `*', and all can be disallowed with an empty string (`'). Options 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. 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: 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 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: // 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: // 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 fuchsia-virtual-inheritance Warns if classes are defined with virtual inheritance. For example, classes should not be defined with virtual inheritance: class B : public virtual A {}; // warning See the features disallowed in Fuchsia at https://fuchsia.googlesource.com/zircon/+/master/docs/cxx.md 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. 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 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). google-build-using-namespace Finds using namespace directives. The check implements the following rule of the Google C++ Style Guide: You may not use a using-directive to make all names from a namespace available. // Forbidden -- This pollutes the namespace. using namespace foo; Corresponding cpplint.py check name: build/namespaces. google-default-arguments Checks that default arguments are not given for virtual methods. See https://google.github.io/styleguide/cppguide.html#Default_Arguments 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: 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: struct S { S(int a); explicit S(const S&); operator bool() const; ... will become struct S { explicit S(int a); S(const S&); explicit operator bool() const; ... See https://google.github.io/styleguide/cppguide.html#Explicit_Constructors 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 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). 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: - (void)readFile { if ([self isError]) { @throw [NSException exceptionWithName:...]; } } Instead, returning an error via NSError ** is preferred: - (BOOL)readFileWithError:(NSError **)error { if ([self isError]) { *error = [NSError errorWithDomain:...]; return NO; } return YES; } The corresponding style guide rule: http://google.github.io/styleguide/objcguide.html#avoid-throwing-exceptions 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: 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: static bool IsPositive(int i) { return i > 0; } bool *ABCIsNegative(int i) { return i < 0; } 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: http://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: static NSString* myString = @"hello"; The fix will be: static NSString* gMyString = @"hello"; Another example of constant: static NSString* const myConstString = @"hello"; The fix will be: static NSString* const kMyConstString = @"hello"; However for code that prefixed with non-alphabetical characters like: static NSString* __anotherString = @"world"; The check will give a warning message but will not be able to suggest a fix. The user need to fix it on his own. google-readability-braces-around-statements The google-readability-braces-around-statements check is an alias, please see readability-braces-around-statements for more information. 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. google-readability-function-size The google-readability-function-size check is an alias, please see readability-function-size for more information. google-readability-namespace-comments The google-readability-namespace-comments check is an alias, please see llvm-namespace-comment for more information. 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 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. Correspondig cpplint.py check: runtime/int. Options UnsignedTypePrefix A string specifying the unsigned type prefix. Default is uint. SignedTypePrefix A string specifying the signed type prefix. Default is int. TypeSuffix A string specifying the type suffix. Default is an empty string. google-runtime-operator Finds overloads of unary operator &. https://google.github.io/styleguide/cppguide.html#Operator_Overloading Corresponding cpplint.py check name: runtime/operator. google-runtime-references Checks the usage of non-constant references in function parameters. The corresponding style guide rule: https://google.github.io/styleguide/cppguide.html#Reference_Arguments Options WhiteListTypes A semicolon-separated list of names of whitelist types. Default is empty. hicpp-avoid-c-arrays The hicpp-avoid-c-arrays check is an alias, please see modernize-avoid-c-arrays for more information. hicpp-avoid-goto 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. hicpp-braces-around-statements The hicpp-braces-around-statements check is an alias, please see readability-braces-around-statements for more information. It enforces the rule 6.1.1. hicpp-deprecated-headers The hicpp-deprecated-headers check is an alias, please see modernize-deprecated-headers for more information. It enforces the rule 1.3.3. hicpp-exception-baseclass Ensure that every value that in a throw expression is an instance of std::exception. This enforces rule 15.1 of the High Integrity C++ Coding Standard. 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(); } hicpp-explicit-conversions This check is an alias for google-explicit-constructor. Used to enforce parts of rule 5.4.1. 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: o cppcoreguidelines-pro-type-static-cast-downcast o cppcoreguidelines-pro-type-reinterpret-cast o cppcoreguidelines-pro-type-const-cast o cppcoreguidelines-pro-type-cstyle-cast hicpp-function-size This check is an alias for readability-function-size. Useful to enforce multiple sections on function complexity. o rule 8.2.2 o rule 8.3.1 o rule 8.3.2 hicpp-invalid-access-moved This check is an alias for bugprone-use-after-move. Implements parts of the rule 8.4.1 to check if moved-from objects are accessed. hicpp-member-init This check is an alias for cppcoreguidelines-pro-type-member-init. Implements the check for rule 12.4.2 to initialize class members in the right order. hicpp-move-const-arg The hicpp-move-const-arg check is an alias, please see performance-move-const-arg for more information. It enforces the rule 17.3.1. 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 and rule 6.1.4 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. void f1() { int i = determineTheNumber(); if(i > 0) { // Some Calculation

Search: Section: