c++c++17istringstreamstring-view

Why doesn't std::stringstream work with std::string_view?


The std::stringstream initialization constructor accepts const string& as a parameter:

explicit stringstream (const string& str,
                       ios_base::openmode which = ios_base::in | ios_base::out);

This interface was reasonable in C++98, but since C++17 we have std::string_view as a cheaper alternative of the class representing a string. The std::stringstream class doesn't modify the string it accepts, doesn't own it, it doesn't require from it to be null-terminated. So why not to add another constructor overload that accepts the std::string_view? Are there any obstacles that make this solution impossible (or not reasonable) yielding to alternatives like Boost::Iostreams?


Solution

  • At this point (ie: as we approach C++23), there's just not much point to it.

    Since you used stringstream instead of one of the more usage-specific versions, there are two possibilities: you either intend to be able to write to the stream, or you don't.

    If you don't intend to write to the stream, then you don't need the data to be copied. All forms of stringstream own the characters it acts on, so you should try to avoid the copy. You can use the C++23 type ispanstream (a replacement for the old strstream). This takes a span<const CharT>, but string_view should be compatible with one of ispanstream's constructors too.

    If you do intend to write to the stream, then you will need to copy the data into the stringstream. But you need not perform two copies. So C++20 gives stringstream a move-constructor from a std::string. See constructor #6 here:

    explicit basic_stringstream( std::basic_string<CharT,Traits,Allocator>&& str,
                                 std::ios_base::openmode mode = 
                                 std::ios_base::in | std::ios_base::out );
    
    1. Move-construct the contents of the underlying string device with str. The underlying basic_stringbuf object is constructed as basic_stringbuf<Char,Traits,Allocator>(std::move(str), mode).

    And since std::string is constructable from a string_view, passing a std::string_view into a std::stringstream constructor will use this move-constructor overload, which should minimize copying.

    So there's really no need for a string_view-specific constructor.