Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-6222

"[[nodiscard]]" attributes on types should include explanations

    XMLWordPrintable

    Details

    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Level:
      Syntactic Analysis
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      The [[nodiscard]] attribute can be placed on type declarations to indicate that any value of such type should not be discarded when returned from a function. Accompanying the attribute with the message, explaining why values should not be ignored, contributes to a better understanding of code. This is especially important in the case of types, as the reason for which values of the type should not be discarded is a defining property of that type (information about failure, handle owning a scarce resource).

      Moreover, marking a type as nodiscard, causes a warning to be reported for invocation of every function that returns this type. As a consequence, the cause of the warning is not directly visible from the declaration of the function and requires further investigation from the user.

      This rule raises an issue when [[nodiscard]] is used on a type without any explanation.

      Noncompliant Code Example

      struct [[nodiscard]] status_code {  // Noncompliant
         int code();
      };
      
      status_code open(std::string_view path);
      
      int main()
      {
         open("/home/user/list.txt");  // warning is raised here
      }
      

      Compliant Solution

      struct [[nodiscard("Possible errors should be checked")]] status_code { 
         int code();
      };
      

      See

      • S6166 - introducing messages for [[nodiscard]] on functions
      • S6007 - marking functions as [[nodicard]]

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              tomasz.kaminski Tomasz KamiƄski
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: