Uploaded image for project: 'SonarCFamily'
  1. SonarCFamily
  2. CPP-2939

Rule S6188: "std::span" should be used for a uniform sequence of elements contiguous in memory

    XMLWordPrintable

    Details

    • Type: New Feature
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 6.19
    • Component/s: C++, Rules
    • Labels:

      Description

      Detect when a function takes arguments Pointer + length or begin_ptr, end_ptr that really should've been an std::span.

      Detect if a function is overloaded for any two of the four: plain array, pointer with a size, std::array, std::vector.

      Beware, that specialization for static arrays might benefit from optimizations such as loop-unrolling and inlining, so in general it should be replaced with the specialization for std::span with static extent (templated), and is probably not worth the trouble refactoring, because it might require explicit std::span construction at the call site:

      template<std::size_t size>
      void addOdd(std::array<int, size>* v) { // Noncompliant: replace the 2 overloads with one for std::span
        for (int i = 0; i*2 + 1 < std::size(*v); ++i) {
          v->at(i*2) += v->at(i*2 + 1);
        }
      }
      

      has to be rewritten as

      template<std::size_t size>
      void addOdd(std::span<int, size> v) { // Noncompliant: replace the 2 overloads with one for std::span
        for (int i = 0; i*2 + 1 < std::size(v); ++i) {
          v[i*2] += v[i*2 + 1];
        }
      }
      

      to preserve the optimization opportunities. this means that the caller will have to write

      addOdd(std::span{arr})
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              amelie.renard Amélie Renard
              Reporter:
              arseniy.zaostrovnykh Arseniy Zaostrovnykh
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Due:
                Created:
                Updated:
                Resolved: