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

"std::bit_cast" should be used to reinterpret binary representation instead of "std::memcpy"

    XMLWordPrintable

    Details

    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C++
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Level:
      Semantic Analysis
    • Analysis Scope:
      Main Sources, Test Sources

      Description

      std::bit_cast is one of the standard functions working with the binary representation. Together with other bit-level functions, it is defined in the <bits> header introduced by C++20.

      std::bit_cast standardizes the diverse and sub-optimal approaches of reinterpreting a value as being of a different type of the same length preserving its binary representation.

      Before C++20 the correct way to reinterpret a value was a call to std::memcpy, copying the exact binary representation from a variable of one type into a variable of another. Although canonical, the use of std::memcpy might still be confusing, it is verbose, and it might introduce performance overhead if the compiler does not recognize the idiom and does not remove the function call.

      In contrast, std::bit_cast clearly states the intent and is guaranteed to map to an optimal implementation.

      This rule reports the uses of std::memcpy that can be replaced by std::bit_cast.

      Noncompliant Code Example

      static_assert(sizeof(float) == sizeof(uint32_t));
      float src = 1.0f;
      uint32_t dst;
      std::memcpy(&dst, &src, sizeof(float)); // Noncompliant: verbose and might incur performance hit
      

      Compliant Solution

      float src = 1.0f;
      auto dst = std::bit_cast<uint32_t>(src); // Compliant
      

      See

      Other common patterns predating C++20:

      • S3630 - replacing std::reinterpret_cast with std::bit_cast.
      • S871 - replacing C-style cast with std::bit_cast.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              arseniy.zaostrovnykh Arseniy Zaostrovnykh
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: