std::fstream & co. should be constructible from string_view
Jonathan Wakely

Created on 2020-04-15.00:00:00 last changed 3 months ago


Date: 2020-05-15.00:00:00

[ 2020-05-09; Reflector prioritization ]

Set priority to 3 after reflector discussions.

Date: 2020-04-15.00:00:00

We have:

basic_fstream(const char*, openmode);
basic_fstream(const filesystem::path::value_type*, openmode); // wide systems only
basic_fstream(const string&, openmode);
basic_fstream(const filesystem::path&, openmode);

I think the omission of a string_view overload was intentional, because the underlying OS call (such as fopen) needs a NTBS. We wanted the allocation required to turn a string_view into an NTBS to be explicitly requested by the user. But then we added the path overload, which is callable with a string_view. Converting to a path is more expensive than converting to std::string, because a path has to at least construct a basic_string, and potentially also does an encoding conversion, parses the path, and potentially allocates a sequence of path objects for the path components.

This means the simpler, more obvious code is slower and uses more memory:

string_view sv = "foo.txt";
fstream f1(sv); // bad
fstream f2(string(sv)); // good

We should just allow passing a string_view directly, since it already compiles but doesn't do what anybody expects or wants.

Even with a string_view overload, passing types like const char16_t* or u32string_view will still implicitly convert to filesystem::path, but that seems reasonable. In those cases the encoding conversion is necessary. For Windows we support construction from const wchar_t* but not from wstring or wstring_view, which means those types will convert to filesystem::path. That seems suboptimal, so we might also want to add wstring and wstring_view overloads for "wide systems only", as per [fstream.syn] p3.


LWG 2883 has a more general view on that but does not consider potential cost differences in the presence of path overloads (Which didn't exist at this point yet).

Date User Action Args
2020-05-09 19:18:02adminsetmessages: + msg11274
2020-04-15 00:00:00admincreate