[英]convert pid_t to const char* with stringstream
I want to convert a process pid to a const char* but below does not work: 我想将进程pid转换为const char *,但以下方法不起作用:
std::ostringstream str_pid;
str_pid << getpid();
const char * cstr_pid = str_pid.str().c_str();
It works most of the time but sometimes it has a false result. 它在大多数情况下都有效,但有时会产生错误的结果。 Apparently i am doing something wrong.
显然我在做错事。 Any idea?
任何想法?
cstr_pid
will be a dangling pointer, as the temporary std::string
returned by str_pid.str()
is destructed after the assignment of cstr_pid
. cstr_pid
将是一个悬空指针,因为分配了cstr_pid
之后, str_pid.str()
返回的临时std::string
被破坏。 Create a copy of the str_pid.str()
return value: 创建
str_pid.str()
返回值的副本:
const std::string my_pid(str_pid.str());
then use my_pid.c_str()
when const char*
is required. 然后在需要
const char*
时使用my_pid.c_str()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.