Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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. And since std::string is convertible from a string_view, it will use the move-constructor overload, which should minimize copying.

So there’s really no place for a string_view-specific constructor.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading