Why is this an issue?
std::format
takes as an argument a format string that contains replacement fields (surrounded with {}
) and a set of extra
arguments that will be formatted inside the replacement fields. Even if the format string is checked at compile-time, it is possible to have a
mismatch between the format string and the arguments. For example:
- The format string contains fewer replacement fields than the number of extra arguments:
std::format("{} {}", 1, 2, 3);
- The format string uses indexes for the replacement fields, but one index is missing:
std::format("{0} {0} {2}", 1, 2, 3);
In these cases, the extra arguments are silently ignored. In the best-case scenario, it leads to dead code. Otherwise, it is a typo, and the output
will not be intended.
How to fix it
This rule raises an issue when:
- An unused argument comes from a complex expression, such as a function call.
- A combination of numbered replacement fields, a missing index, and a repeated index exists.
Code examples
Noncompliant code example
std::cout << std::format("{} {}", 1, 2, sqrt(2)); // Noncompliant
std::cout << std::format("{0} {0} {2}", 1, 2, 3); // Noncompliant
Compliant solution
std::cout << std::format("{} {} {}", 1, 2, sqrt(2)); // Compliant
std::cout << std::format("{0} {0} {2} {1}", 1, 2, 3); // Compliant
Resources
- {rule:cpp:S6488} - To detect all unused arguments in
std::format
.