The only (simple) portable way includes making the copy:
std::istringstream ss(std::string(buf,len));
In fact, this is likely to copy the data twice, once to create the string
and once to create the istringstream
. (Maybe C++11 can avoid one of the copies via a move constructor; I am not sure.)
However, if you are lucky, your C++ implementation will let you do this:
std::istringstream ss;
ss.rdbuf()->pubsetbuf(buf,len);
Under GNU C++ (and, I believe, some other implementations), this will create the stringstream without copying the data. But this is "implementation-defined" behavior according to the spec. (See also this question.)
By including the len
parameter, you ensure that both of these will have no problem with null characters.
The only portable way to do what you want is to implement your own subclass of stringbuf
and use it to initialize the stringstream. Not for the faint of heart.
std::string(buffer, buffer + buffer_size)
, this doesn't get around the copying problem though. – Concoff