3

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.

4

1 回答 1

5

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 进行打印,并在不必要时停止使用低级指针:)

于 2012-10-31T13:24:04.523 回答