3651. Unspecified lifetime guarantees for the format string

Section: 28.5 [format] Status: New Submitter: Barry Revzin Opened: 2021-12-08 Last modified: 2022-01-30

Priority: 3

View all issues with New status.

Discussion:

Is this program guaranteed to be valid:

#include <format>
#include <algorithm>

struct Thing { };

template <>
struct std::formatter<Thing> {
  std::string_view spec;

  constexpr auto parse(std::format_parse_context& ctx) {
    auto end = std::find(ctx.begin(), ctx.end(), '}');
    spec = std::string_view(ctx.begin(), end);
    return end;
  }

  auto format(Thing, std::format_context& ctx) {
    return std::ranges::copy(spec, ctx.out()).out;
  }
};

int main() {
  std::print("{:lwg issue}\n",  Thing{});
}

In parse(), the formatter for Thing holds onto a string view of its specifiers. And then in format(), it just prints them. I don't think we say anywhere that this works. Does this code print "lwg issue" because there's no issue or does it print some garbage memory somewhere because there is one?

libfmt's implementation internally stores string_view's into the format string (for named argument support), which implies that it should work. But it'd be nice to come out and say that.

[2022-01-30; Reflector poll]

Set priority to 3 after reflector poll.
"Presumably we need to say in [formatter.requirements] that [pc.begin(), pc.end()) is guaranteed to be a valid range until the next call to parse() or f is destroyed, whichever comes first."

Proposed resolution: