I know you can't extract an std::string
from an std::ostringstream
without copying (Creating an input stream from constant memory).
But is it possible to get an std::string_view
?
Why use std::string_view ? string_view is useful when you want to avoid unnecessary copies. String_views are less memory-intensive to construct and copy. The creation of string_view from literals does not require a dynamic allocation.
std::string_view provides read-only access to an existing string (a C-style string literal, a std::string , or a char array) without making a copy.
What Is the StringStream Class? The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.
The std::string has some demerits, one of the most common situations is constant strings. Below is the program that demonstrates the problem that occurs in dealing with constant strings with std::string:
Going the other way, to get a string_view from a string (so to get a pointer to that string) you can do this: string s; string_view sv = string_view (s); Note that substring and a variety of other operations can be performed on string_view just as on string.
The std::string constructor is explicit, so beginners can be confused as why a string cannot be constructed with a string view without typing std::string to convert it. std::string has constructors that will accept a std::string_view as input, eg:
std::string_view: C++17 library has proposed a standard type of string ( std::string_view) which is different from the usual std::string.
String-streams are not required to store their data in a single contiguous array. string_view
is of course a view into a contiguous string.
So no, what you want is not possible. Best wait till C++20, when we get move support into/outof string-streams.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With