简体   繁体   English

奇怪的const char *行为

[英]Strange const char* behaviour

GetTypeName is std::string, the following code 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);

produces this output: 产生这个输出:

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

addresses are always the same; 地址总是一样的; the following code (lines are exchanges) 以下代码(行是交换)

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

produces this output, addresses are always different: 产生这个输出,地址总是不同的:

0x57ef78
  Y
0x580850
ValidTypeName

What am I doing wrong? 我究竟做错了什么?

strlen(res)

returns invalid size, so I can't even strcpy. 返回无效大小,所以我甚至不能strcpy。

YourGetTypeName function is returning an std::string and you are calling c_str to get a pointer to the internal data in that string. YourGetTypeName函数返回一个std :: string,您正在调用c_str来获取指向该字符串中内部数据的指针。

As it's a temporary the std::string you return will be deleted at the end of the statement 因为它是一个临时的,你返回的std :: string将在语句末尾被删除

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

But you still have res pointing to the now deleted data. 但你仍然有res指向现在删除的数据。

Edit: Change your code to something like :- 编辑:将您的代码更改为: -

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

and call .c_str() on that string in the printf like this :- 并在printf中的字符串上调用.c_str(),如下所示: -

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

Assigning a temporary to a reference extends the lifetime of that temporary to be the same as the lifetime of the reference... 将临时值分配给引用会将该临时值的生命周期延长为与引用的生命周期相同...

Better still, just use std::string and iostream for printing and stop messing about with low level pointers when unnecessary :) 更好的是,只需使用std :: string和iostream进行打印,并在不必要的时候停止使用低级指针搞乱:)

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

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