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。
不會返回一個const std :: string&work? – amaurea
@amaurea:可能,但它有一個缺點:http://stackoverflow.com/a/134777/166749 –
使用移動語義,爲什麼不把返回的字符串存儲在實際的字符串中?然後有人看着代碼就不必知道GetTypeName的簽名來驗證字符串的生命週期...... – Yakk