This is fine:
// This creates a temp string
std::string temp = std::to_string(channel_id2);
// This is fine, because temp is a variable (and so exists in memory)
const char *sz2 = temp.c_str();
然而,如果是的话:
const char *sz2 = std::to_string(channel_id2).c_str();
行动顺序是:
- Call
std::to_string
, which generates a temporary string object.
- Use
c_str()
to get a pointer to the temporary string contents
- Free the temporary string (thus freeing the memory that sz2 is pointing too)
其结果是,sz2无所作为,因此,你获得了不实的印本。
或者说要把你的一条法典跨过多个方面,这就是:
const char *sz2; //< uninitialised
// scope the lifespan of the temporary
{
// generate temp
std::string temp = std::to_string(channel_id2);
// grab address..
sz2 = temp.c_str();
// at this point, the destructor of temp is called...
}
// now sz2 is invalid from here