How to get characters out of stringstream without copy?
c++, c++11, stringstream
Solution
You could use something like described in this link: How to create a std::string directly from a char* array without copying?
Basically, create a string, call the resize() method on the string with the size that is passed to your function and then pass the pointer to the first character of the string to the stringstring.get() method. You will end up with only one copy.
inline std::string left(std::stringstream& ss, uint32_t count) {
std::string str;
str.resize(count);
ss.get(&str[0], count);
return str;
}
Problem
What is the proper c++11 way to extract a set of characters out of a stringstream without using boost? I want to do it without copying, if possible, because where this is used is in a critical data loop. It seems, though, std::string does not allow direct access to the data. For example, the code below performs a substring copy out of a stringstream: ``` inline std::string left(std::stringstream ss, uint32_t count) { char* buffer = new char[count]; ss.get(buffer, count); std::string str(buffer); // Second copy performed here delete buffer; return str; } ``` - Should I even be using char *buffer according to c++11? - How do I get around making a second copy? My understanding is that vectors initialize every character, so I want to avoid that. Also, this needs to be passed into a function which accepts const char *, so now after this runs I am forced to do a .c_str(). Does this also make a copy? It would be nice to be able to pass back a const char *, but that seems to go against the "proper" c++11 style. To understand what I am trying to do, here is "effectively" what I want to use it for: ``` fprintf( stderr, "Data: [%s]...", left(ststream, 255) ); ``` But the c++11 forces: ``` fprintf( stderr, "Data: [%s]...", left(str_data, 255).c_str() ); ``` How many copies of that string am I making here? How can I reduce it to only a single copy out of the stringstream?