ArmanHunanyan ArmanHunanyan - 28 days ago 7
C++ Question

Constructing stream witout copying buffer

I have a code like:

char* text = ....
std::istringstream iss(text);


I know that here temporary std::string is constructed and it one more time is copied inside stringstream object. Is there a way to construct stream from char* without making copy of string.

Answer

Historically, this functionality was provided by the now deprecated std::istrstream:

The class istrstream implements input operations on array-backed streams. It essentially wraps a raw array I/O device implementation (std::strstreambuf) into the higher-level interface of std::basic_istream.

The typical implementation of istrstream holds only one non-derived data member: an object of type std::strstreambuf.

Notes

istrstream has been deprecated since C++98, std::istringstream and boost::iostreams::array_source are the recommended replacements.

Thus, a current implementation meeting your requirements is boost::iostreams::array_source:

Overview

The class templates basic_array_source, basic_array_sink and basic_array provide access to a sequence of characters in memory. The array Devices do not manage the lifetimes of the underlying character sequences.

Implementation

The array Devices are implemented as Direct Devices in order to provide efficient unbuffered access to the underlying character sequences.