繁体   English   中英

奇怪的const char *行为

[英]Strange const char* behaviour

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);

产生这个输出:

0x90ef78
ValidTypeName
0x90ef78
ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■ю■←ЬЬQщZ

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

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());

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

0x57ef78
  Y
0x580850
ValidTypeName

我究竟做错了什么?

strlen(res)

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

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

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

const char *res = proto->GetTypeName().c_str();

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

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

const std::string& res = proto->GetTypeName(); 

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

printf("%#x\n",res.c_str());
printf("%s\n",res.c_str());

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM