3
#include <sstream>

using namespace std;

const char* GetHugeString();

int main()
{
    const char* p = GetHugeString();

    //
    // Below will copy the huge string into a std::string object!
    // 
    istringstream sstrm{p}; 

    return {};
}

istringstream doesn't need a copy of the huge string; a null-terminated string pointer is enough. But istringstream's ctor only take std::string, rather than std::string_view(c++1z only), as its argument.

Is there a work-around to make std::istringstream more efficient in such a case?

xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • I'm not sure is this is the reason, but I suspect this isn't supported because the internal storage is backed by `stringbuf`, which doesn't accept `string_view` (for good reason). – Collin Dauphinee Dec 07 '16 at 04:39

1 Answers1

3

You can simply assign the buffer used internally in the istringstream:

istringstream stream;
stream.rdbuf()->pubsetbuf(p, strlen(p));

This does not copy the string. Do note that pubsetbuf() wants char* not const char*, but it doesn't actually modify the string, so you might const_cast your C string pointer before passing it.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 4
    What you're suggesting [has implementation-defined behavior](http://stackoverflow.com/a/13059195/636019). – ildjarn Dec 07 '16 at 04:42