Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to get an std::string_view from an std::ostringstream without copying?

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?

like image 323
Ryan Burn Avatar asked Nov 04 '17 20:11

Ryan Burn


People also ask

Why use 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.

What is std::string_view?

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 Istringstream C++?

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.

Where is StringStream defined?

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.

Is it possible to deal with constant strings with std::string?

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:

How do I get a string_view from a 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.

Why can't a string be constructed with a string view?

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:

What is string_view in C++17?

std::string_view: C++17 library has proposed a standard type of string ( std::string_view) which is different from the usual std::string.


1 Answers

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.

like image 175
Nicol Bolas Avatar answered Nov 03 '22 01:11

Nicol Bolas