Title
Unspecified lifetime guarantees for the format string
Status
new
Section
[format]
Submitter
Barry Revzin

Created on 2021-12-08.00:00:00 last changed 1 month ago

Messages

Date: 2021-12-11.16:29:27

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.

History
Date User Action Args
2021-12-08 00:00:00admincreate