奇怪的const char*行为

Dim*_*nnn 3 c++ const char

GetTypeName是std :: string,代码如下

printf("%#x\n", proto->GetTypeName().c_str());
printf("%s\n", proto->GetTypeName().c_str());
const char *res = proto->GetTypeName().c_str();
printf("%#x\n",res);
printf("%s\n",res);
Run Code Online (Sandbox Code Playgroud)

产生这个输出:

0x90ef78
ValidTypeName
0x90ef78
???????????????????????????????????????????????????????????Q?Z
Run Code Online (Sandbox Code Playgroud)

地址总是一样的; 以下代码(行是交换)

const char *res = proto->GetTypeName().c_str();
printf("%#x\n",res);
printf("%s\n",res);
printf("%#x\n", proto->GetTypeName().c_str());
printf("%s\n", proto->GetTypeName().c_str());
Run Code Online (Sandbox Code Playgroud)

产生这个输出,地址总是不同的:

0x57ef78
  Y
0x580850
ValidTypeName
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

strlen(res)
Run Code Online (Sandbox Code Playgroud)

返回无效大小,所以我甚至不能strcpy.

jco*_*der 5

YourGetTypeName函数返回一个std :: string,您正在调用c_str来获取指向该字符串中内部数据的指针.

因为它是一个临时的,你返回的std :: string将在语句末尾被删除

const char *res = proto->GetTypeName().c_str();
Run Code Online (Sandbox Code Playgroud)

但你仍然有res指向现在删除的数据.

编辑:将您的代码更改为: -

const std::string& res = proto->GetTypeName(); 
Run Code Online (Sandbox Code Playgroud)

并在printf中的字符串上调用.c_str(),如下所示: -

printf("%#x\n",res.c_str());
printf("%s\n",res.c_str());
Run Code Online (Sandbox Code Playgroud)

将临时值分配给引用会将该临时值的生命周期延长为与引用的生命周期相同...

更好的是,只需使用std :: string和iostream进行打印,并在不必要的时候停止使用低级指针搞乱:)