I have some code similar to this:
std::istringstream iss{"SomeChars"};
// Some read ops here (though the problem stays even without them)
std::string reconst(iss.str().cbegin(), iss.str().cbegin() iss.tellg());
std::cout << reconst << std::endl;
The result is always some garbled string. Here is a program demonstrating this.
The program works when I store iss.str()
in a std::string_view
or std::string
. However, I still have my question:
Questions:
- Why does the program behave this way?
- I can't see how it would be interpreted this way, but is this the most vexing parse?
CodePudding user response:
The str
function returns the string by value. That means each call to str
gives you a new string object, and your iterators are pointing to those temporary strings, not the string that is the buffer for the stringstream. This cant work, because the iterators need to point into the same object, not different objects that have the same value.