Introduced in C++17, the class std::filesystem::path
can 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. It can also be more efficient since conversion from string
to path
may require a change of encoding and 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
}
}