use*_*655 2 c++ string pid stringstream
我想将进程 pid 转换为 const char* 但下面不起作用:
std::ostringstream str_pid;
str_pid << getpid();
const char * cstr_pid = str_pid.str().c_str();
Run Code Online (Sandbox Code Playgroud)
它在大多数情况下都有效,但有时会产生错误的结果。显然我做错了什么。任何想法?
cstr_pid将是一个悬空指针,因为std::string返回的临时指针str_pid.str()在分配后被破坏cstr_pid。创建返回值的副本str_pid.str():
const std::string my_pid(str_pid.str());
Run Code Online (Sandbox Code Playgroud)
然后在需要的my_pid.c_str()时候使用const char*。