SonarSource Rules
  • Products

    In-IDE

    Code Quality and Security in your IDE with SonarQube Ide

    IDE extension that lets you fix coding issues before they exist!

    Discover SonarQube for IDE

    SaaS

    Code Quality and Security in the cloud with SonarQube Cloud

    Setup is effortless and analysis is automatic for most languages

    Discover SonarQube Cloud

    Self-Hosted

    Code Quality and Security Self-Hosted with SonarQube Server

    Fast, accurate analysis; enterprise scalability

    Discover SonarQube Server
  • SecretsSecrets
  • ABAPABAP
  • AnsibleAnsible
  • ApexApex
  • AzureResourceManagerAzureResourceManager
  • CC
  • C#C#
  • C++C++
  • CloudFormationCloudFormation
  • COBOLCOBOL
  • CSSCSS
  • DartDart
  • DockerDocker
  • FlexFlex
  • GitHub ActionsGitHub Actions
  • GoGo
  • HTMLHTML
  • JavaJava
  • JavaScriptJavaScript
  • JSONJSON
  • JCLJCL
  • KotlinKotlin
  • KubernetesKubernetes
  • Objective CObjective C
  • PHPPHP
  • PL/IPL/I
  • PL/SQLPL/SQL
  • PythonPython
  • RPGRPG
  • RubyRuby
  • RustRust
  • ScalaScala
  • ShellShell
  • SwiftSwift
  • TerraformTerraform
  • TextText
  • TypeScriptTypeScript
  • T-SQLT-SQL
  • VB.NETVB.NET
  • VB6VB6
  • XMLXML
  • YAMLYAML
C++

C++ static code analysis

Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your C++ code

  • All rules 674
  • Vulnerability13
  • Bug139
  • Security Hotspot19
  • Code Smell503

  • Quick Fix 91
Filtered: 118 rules found
pitfall
    Impact
      Clean code attribute
        1. "goto" should jump to labels declared later in the same function

           Code Smell
        2. The name "main" should not be used for any function other than the global "main" function

           Code Smell
        3. Dynamic heap memory allocation should not be used

           Bug
        4. "setjmp" and "longjmp" should not be used

           Code Smell
        5. Macros should not be #define'd or #undef'd within a block

           Code Smell
        6. Array type function arguments should not decay to pointers

           Code Smell
        7. Object declarations should contain no more than 2 levels of pointer indirection

           Code Smell
        8. Recursion should not be used

           Code Smell
        9. Functions should not be defined with a variable number of arguments

           Code Smell
        10. The loop-counter should be modified by one of: --, ++, -=n, or +=n; where n remains constant for the duration of the loop

           Code Smell
        11. C-style and functional notation casts should not be used

           Code Smell
        12. Constants of unsigned type should have a "U" suffix

           Code Smell
        13. If a function has internal linkage then all re-declarations shall include the static storage class specifer

           Code Smell
        14. Literal suffix "L" for long integers shall be upper case

           Code Smell
        15. "std::views::as_const" should be used to prevent modifying range elements

           Code Smell
        16. "std::stringstream" or "std::spanstream" should be used instead of "std::strstream"

           Code Smell
        17. The underlying value of an enum should be accessed through "to_underlying"

           Code Smell
        18. The optional init-statement in a control statements should only be used to declare variables

           Code Smell
        19. Macro arguments should not contain preprocessing directives

           Bug
        20. All the elements of an aggregate should be provided with an initial value

           Code Smell
        21. Coroutines should have well-defined exception behavior

           Bug
        22. Use symmetric transfer to switch execution between coroutines

           Code Smell
        23. rvalue reference members should not be copied accidentally

           Code Smell
        24. Well-defined type-punning method should be used instead of a union-based one

           Bug
        25. Comparision operators ("<=>", "==") should be defaulted unless non-default behavior is required

           Code Smell
        26. "std::cmp_*" functions should be used to compare unsigned values with negative values

           Bug
        27. Function template parameters should be named if reused

           Code Smell
        28. Redundant comparison operators should not be defined

           Code Smell
        29. "std::cmp_*" functions should be used to compare signed and unsigned values

           Code Smell
        30. "std::bit_cast" should be used to reinterpret binary representation instead of "std::memcpy"

           Code Smell
        31. "std::midpoint" and "std::lerp" should be used for midpoint computation and linear interpolation

           Code Smell
        32. Designated initializers should be used in their C++ compliant form

           Code Smell
        33. Use discriminated unions or "std::variant"

           Code Smell
        34. The right template argument should be specified for std::forward

           Code Smell
        35. Exception specifications should be treated as part of the type

           Code Smell
        36. Use "std::variant" instead of unions with non-trivial types.

           Code Smell
        37. "std::byte" should be used when you need byte-oriented memory access

           Code Smell
        38. "[*this]" should be used to capture the current object by copy

           Code Smell
        39. Macros should not be used as replacements for "typedef" and "using"

           Code Smell
        40. Member functions that don't mutate their objects should be declared "const"

           Code Smell
        41. Multiple mutexes should not be acquired with individual locks

           Code Smell
        42. Local variables should be initialized immediately

           Code Smell
        43. "try_lock", "lock" and "unlock" should not be directly used for mutexes

           Code Smell
        44. A single statement should not have more than one resource allocation

           Code Smell
        45. Function parameters that are rvalue references should be moved

           Code Smell
        46. Functions should not have more than one argument of type "bool"

           Code Smell
        47. Non-const global variables should not be used

           Code Smell
        48. The order for arguments of the same type in a function call should be obvious

           Code Smell
        49. Classes should not contain both public and private data members

           Code Smell
        50. A call to "wait()" on a "std::condition_variable" should have a condition

           Bug
        51. Class members should not be initialized with dangling references

           Bug
        52. Keywords shall not be used as macros identifiers

           Code Smell
        53. Logical operators should not be confused with bitwise operators

           Code Smell
        54. The addresses of standard library functions should not be taken

           Code Smell
        55. Lambdas that capture "this" should capture everything explicitly

           Code Smell
        56. Include directives should not rely on non-portable search strategy

           Code Smell
        57. "#include" paths should be portable

           Code Smell
        58. Exceptions should not be thrown in "noexcept" functions

           Code Smell
        59. Array indices should be placed between brackets

           Code Smell
        60. Virtual functions should not have default arguments

           Code Smell
        61. Comparison operators should not be virtual

           Code Smell
        62. Alternative operators should not be used

           Code Smell
        63. Assignment operators should not be "virtual"

           Code Smell
        64. Member variables should not be "protected"

           Code Smell
        65. Scoped enumerations should be used

           Code Smell
        66. "reinterpret_cast" should not be used

           Code Smell
        67. Classes should have regular copy and move semantic

           Code Smell
        68. Standard groupings should be used with digit separators

           Code Smell
        69. Bit fields should not be used

           Code Smell
        70. Conditionally executed code should be reachable

           Bug
        71. Control characters should not be used in literals

           Code Smell
        72. Octal and hexadecimal escape sequences should be terminated

           Code Smell
        73. "static" members should be accessed statically

           Code Smell
        74. Member variables should be initialized

           Bug
        75. Preprocessor directives should not be indented

           Code Smell
        76. "goto" statements should not be used to jump into blocks

           Code Smell
        77. Related "if/else if" statements should not have the same condition

           Bug
        78. "switch" statements should not be nested

           Code Smell
        79. A "struct" should not have member functions

           Code Smell
        80. The sign of an unsigned variable should not be tested

           Code Smell
        81. Virtual functions should not be called from constructors or destructors

           Code Smell
        82. Context-sensitive keywords should not be used as identifiers

           Code Smell
        83. Octal values should not be used

           Code Smell
        84. "::" operator should be used to access global variables and functions

           Code Smell
        85. "for" loop stop conditions should be invariant

           Code Smell
        86. Control structures should use curly braces

           Code Smell
        87. Variables should not be shadowed

           Code Smell
        88. Control should not be transferred into a complex logic block using a "goto" or a "switch" statement

           Code Smell
        89. Pure "virtual" functions should not override non-pure "virtual" functions

           Code Smell
        90. Parameters in an overriding virtual function shall either use the same default arguments as the function they override, or else shall not specify any default arguments

           Code Smell
        91. "using-directives" should not be used

           Code Smell
        92. Header files should not contain unnamed namespaces

           Code Smell
        93. The character handling functions from "<cctype>" and "<cwctype>" shall not be used

           Code Smell
        94. An "integer-literal" of type "long long" shall not use a single "L" or "l" in any suffix

           Code Smell
        95. A non-"transient lambda" shall not implicitly capture "this"

           Code Smell
        96. "std::vector" should not be specialized with "bool"

           Code Smell
        97. The "setlocale" and "std::locale::global" functions shall not be called

           Code Smell
        98. "Unscoped enumerations" should not be declared

           Code Smell
        99. "Advanced memory management" shall not be used

           Code Smell
        100. All variables should be initialized

           Code Smell
        101. An object shall not be used while in a "potentially moved-from state"

           Code Smell
        102. "Forwarding references" and "std::forward" shall be used together

           Code Smell
        103. Variables should be captured explicitly in a non-"transient lambda"

           Code Smell
        104. The macro "offsetof" shall not be used

           Code Smell
        105. The standard "header file" "<csetjmp>" shall not be used

           Code Smell
        106. An "empty throw" shall only occur within the "compound-statement" of a "catch handler"

           Code Smell
        107. An exception object shall not have pointer type

           Bug
        108. A named bit-field with "signed integer type" shall not have a length of one bit

           Bug
        109. There should be no unnamed namespaces in "header files"

           Code Smell
        110. The identifier "main" shall not be used for a function other than the global function "main"

           Code Smell
        111. The "goto" statement shall jump to a label declared later in the function body

           Code Smell
        112. The "address-of" operator shall not be overloaded

           Code Smell
        113. C-style casts and "functional notation" casts shall not be used

           Code Smell
        114. The "declaration" of an object should contain no more than two levels of pointer indirection

           Code Smell
        115. The names of the "standard signed integer types" and "standard unsigned integer types" should not be used

           Code Smell
        116. Tokens that look like a preprocessing directive shall not occur within a macro argument

           Bug
        117. Function-like macros shall not be defined

           Code Smell
        118. Unsigned "integer literals" shall be appropriately suffixed

           Code Smell

        Classes should have regular copy and move semantic

        intentionality - complete
        maintainability
        Code Smell
        • leak
        • cert
        • pitfall

        When a class cannot follow the Rule of Zero, its special members should follow one of a few logical patterns.

        Why is this an issue?

        More Info

        Most classes should not directly handle resources, but instead, use member variables of a type that wraps individual resources and do resource handling for them:

        • For memory, it can be std::unique_ptr, std::shared_ptr, std::vector…​
        • For files, it can be std::ofstream, std::ifstream…​
        • …​

        Classes that avoid directly handling resources don’t need to define any of the special member functions required to properly handle resources: destructor, copy constructor, move constructor, copy assignment operator, and move assignment operator. That’s because the versions of those functions provided by the compiler do the right thing automatically, which is especially useful because writing these functions correctly is typically tricky and error-prone.

        Omitting all of these functions from a class is known as the Rule of Zero because no special function should be defined. This rule should apply to the vast majority of classes.

        // Compliant: vector and unique_ptr handle the resources for us
        //            we don't need to declare any special member function
        class RuleOfZero {
        public:
          void useResource();
          void addValue(Value const& value);
          Value getValueAtIndex(int index);
        private:
          std::unique_ptr<Resource> resource = std::make_unique<Resource>();
          std::vector<Value> values;
        };
        

        The remaining classes that cannot use the Rule of Zero should be dedicated to managing a specific kind of resource and should follow a few logical rules:

        • Copy operations only make sense when the corresponding move operations are available. That is because move operations are optimized copy operations allowed to steal resources from the source (the source is an r-value). At worst, copying is a valid implementation of move operations.
        • Copy and move assignment operators only make sense when the corresponding constructor is available.
        • If you need to customize one of the special member functions, it means that you directly handle resources and the other special member functions probably have a role to play in this resource management. Using = default only performs memberwise operations.

        From these rules, we can describe three categories among which all classes should fall into.

        Copyable classes

        Like most simple classes, these classes can be copied and moved.

        Special member functions for copyable classes

        • Copy construction and move construction should both be available.
        • Either copy assignment and move assignment are both available, or neither is.

        Providing custom special member functions for copyable classes

        If at least one special function needs to be customized, then:

        • You need to provide a custom destructor and a custom copy constructor.
        • The copy assignment needs to be either deleted or customized.
        • If you can optimize the move construction, compared to the copy, you should provide a custom move constructor. Otherwise, you should just omit the move constructor.
        • If the copy assignment is deleted, you need to delete the move assignment.
        • If the copy assignment is customized, you need to provide a move assignment if you can optimize the move operation, compared to the copy. Otherwise, you should just omit the move assignment operator.

        Examples of copyable classes

        // Compliant, no copy assignment operator. Move construction will call the copy constructor.
        class CountedCopyable {
          inline static int count = 0;
        public:
          CountedCopyable() { count++; }
          ~CountedCopyable() { count--; }
          CountedCopyable(CountedCopyable const&) {count ++;}
          CountedCopyable& operator=(CountedCopyable const&) = delete;
        };
        
        // Compliant, all members are declared
        class VerboseCopyable {
        public:
          VerboseCopyable() { std::cout << "Constructor called\n"; }
          ~VerboseCopyable() { std::cout << "Destructor called\n"; }
          VerboseCopyable(VerboseCopyable const&) { std::cout << "Copy constructor called\n"; }
          VerboseCopyable& operator=(VerboseCopyable const&)  { std::cout << "Copy assignment operator called\n"; }
          VerboseCopyable(VerboseCopyable &&) { std::cout << "Move constructor called\n"; }
          VerboseCopyable& operator=(VerboseCopyable &&)  { std::cout << "Move assignment operator called\n"; }
        };
        

        Move-only classes

        These are classes that cannot be copied but can be moved. For example, a class handling a resource that cannot be shared (std::ofstream manages an open file handle) or a class whose objects can be very costly to create.

        Special member functions for move-only classes

        • Move construction is available.
        • Copy construction and copy assignment are not available.
        • Move assignment may be available or not.

        Providing custom special member functions for move-only classes

        • You need to provide a custom destructor and a custom move constructor.
        • The move assignment should be either deleted or customized.

        Examples of move-only classes

        // Compliant, the move assignment operator is implicitly deleted.
        class MoveOnlyResourceHandler {
          Resource resource;
        public:
          MoveOnlyResourceHandler() { resource.open(); }
          ~MoveOnlyResourceHandler() { resource.close(); }
          MoveOnlyResourceHandler(MoveOnlyResourceHandler const& other) { std::swap(other.resource, resource); }
        };
        

        Unmovable classes

        These are classes that cannot be copied, nor moved. They cannot escape their current scope.

        Special member functions for unmovable classes

        All copy and move operations are deleted.

        Examples of unmovable classes

        // Compliant, deleting the move assignment operator implicitly deletes all implicit special member functions
        class UnmovableResource {
          Resource resource;
        public:
          UnmovableResource() { resource.open(); }
          ~UnmovableResource() { resource.close(); }
          UnmovableResource& operator=(UnmovableResource&&) = delete;
        };
        
          Available In:
        • SonarQube IdeCatch issues on the fly,
          in your IDE
        • SonarQube CloudDetect issues in your GitHub, Azure DevOps Services, Bitbucket Cloud, GitLab repositories
        • SonarQube ServerAnalyze code in your
          on-premise CI
          Developer Edition
          Available Since
          9.1

        © 2008-2025 SonarSource SA. All rights reserved.

        Privacy Policy | Cookie Policy | Terms of Use