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

"std::string_view" should be used to pass a read-only string to a function

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Replace this "const std::string&" by "std::string_view".
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Covered Languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Level:
      Semantic Analysis
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      std::string_view is a read-only view over a string, it doesn't hold any data, it only holds a pointer to the first character of the string and its length. std::string_view can offer better performance than std::string in several cases:

      • no memory allocations are required during construction, it is cheap to pass them by value, no need to pass them by reference
      • no heap allocation when passing a string literal to a std::string_view function argument
      • substr operations over a std::string_view do not require memory allocation

      When using std::string_view you shouldn't however forget that:

      • it's a non-owning range, you should keep into consideration the liveness of the pointed range
      • it doesn't guarantee a null-terminated string like std::string

      This rule flags const std::string& function arguments, which can be safely replaced with std::string_view ones when not relying on the null-termination character.

      Note that, if you are calling substr on the parameter, you may have to modify your code to explicitly cast the result to std::string.

      Noncompliant Code Example

      void fun(const std::string& name) { // Noncompliant, replace const std::string& by std::string_view
        // ...
      }
      

      Compliant Solution

      void fun(std::string_view name) {
        // ...
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              massimo.paladin Massimo PALADIN
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: