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

"std::filesystem::path" should be used to represent a file path

    XMLWordPrintable

    Details

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

      Description

      Since C++17, the class std::filesystem::path can be used to store a file path. Compared to a regular string, it offers several advantages:

      • Having a dedicated type makes the intention clear
      • This class stores the path with an encoding that is appropriate to the OS where the program runs
      • It provides several functions that make it more convenient to manipulate than a string (for instance operator/ for concatenations)
      • It provides a normalized way to specify the path, easing the portability of the code (on Windows and Linux, the native way is equivalent to the normalized way, which reduces overhead).

      This rule raises an issue when the same string is converted several times to a path because it indicates that a single path object could have been used in all occurrences. Additionally, it can also be more efficient, since a conversion from string to path may require a change of encoding and a memory allocation.

      Noncompliant Code Example

      std::string getUserData();
      namespace fs = std::filesystem;
      void f() {
        std::string const filePath = getUserData();
        if (fs::exists(filePath)) {
          logTime(fs::last_write_time(filePath)); // Noncompliant
        }
      }
      

      Compliant Solution

      std::string getUserData();
      namespace fs = std::filesystem;
      void f() {
        fs::path const filePath = getUserData();
        if (fs::exists(filePath) {
          logTime(fs::last_write_time(filePath)); // Compliant
        }
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              loic.joly Loïc Joly
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: