简体   繁体   中英

ostringstream to vector<uint8_t>

I've a strange error: I want to copy the content of an ostringstream into a vecotr of unsigned chars:

vector< uint8_t > buffer;
ostringstream os;
os << num1 << char1 << num2 << char2;

// 1. this will crash
buffer.insert( buffer.end(), os.str().begin(), os.str().end() );

// 2. this also crash
copy( os.str().begin(), os.str().end(), back_inserter( buffer );

string str = os.str();

// 4. this work 
buffer.insert( buffer.end(), str().begin(), str().end() );

// 5. this also works
copy( str().begin(), tr().end(), back_inserter( buffer );

I can't understand why 1 and 2 crash on visual studio 2010.

Does someone has some suggest?

The solution is:

vector< uint8_t > buffer;
ostringstream os;
os << num1 << char1 << num2 << char2;

const string& str = os.str();

// 4. this work 
buffer.insert( buffer.end(), str().begin(), str().end() );
os.str().begin()

returns a new temporary string with the contents of os . You take an iterator to the beginning of it.

os.str().end()

returns another temporary string with the contents of os . You take an iterator to the end of it.

The two iterators are not valid since the temporary strings are out of scope now. In addition the iterators also do not belong to the same sequence ( string here ).

What you are doing is almost ( not even considering the dangling iterators ) equivalent to

string str1 = os.str();
string str2 = os.str();

buffer.insert( buffer.end(), str1.begin(), str2.end() );

ostringstream::str() returns a copy of the underlying buffer.

In your cases 1 & 2 you call str() twice (once for begin() and once for end() ) so each resulting iterator relates to different copies of the buffer. Furthermore, those strings are temporaries so they go out of scope immediately, leaving the iterators "dangling".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM