简体   繁体   中英

bada C++ std::stringstream

bada crashed on stringstream read.

json::Object objDocument = d();
std::stringstream stream;
json::Writer::Write(objDocument, stream);
json::Object objDocument2;
json::Reader::Read(objDocument2, stream); // <=== crash

or like this:

std::string *requestString = new std::string(data);
AppLog(requestString->c_str()); // <=== contains correct data
std::stringstream stream;
stream << *requestString;
const char *ddd = stream.str().c_str();
AppLog(ddd); // <==== contains random data

How can I solve it?
Who had ideas or same experience?

The string stream.str() is a temporary which is destroyed right after you use it to get c_str() after which the pointer is no longer valid.

If you save a reference in a temporary the string will stick around:

std::string ddd_str = stream.str();
const char *ddd = ddd_str.c_str();
// ddd_str is still in scope and so ddd is still valid...

The first problem is probably a seek issue. After the write, the current position in the stringstream is at the end, but you want to read from the start.

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