Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Strange Results of String Range Constructor

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading