我正在為游戲撰寫一些代碼,并且正在嘗試撰寫一個輔助函式來回傳物件內的字串:
const char* getGhostName(GhostAI* ghostAI)
{
if (ghostAI) {
GhostInfo* ghostInfo = getGhostInfo(ghostAI);
const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u0A68u0A74u0A6Au0A6F.u0A65u0A66u0A6Eu0A67u0A69u0A74u0A69u0A65u0A74u0A6Fu0A67;
const char* name = il2cppi_to_string(ghostName).c_str();
return name;
}
return "UNKNOWN";
}
這是il2cppi_to_string功能:
std::string il2cppi_to_string(Il2CppString* str) {
std::u16string u16(reinterpret_cast<const char16_t*>(str->chars));
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(u16);
}
std::string il2cppi_to_string(app::String* str) {
return il2cppi_to_string(reinterpret_cast<Il2CppString*>(str));
}
當我打電話時getGhostName,我得到一個空字串。現在我確實收到了來自 ReSharper 的警告,上面寫著:
支持指標的物件將在完整運算式的末尾被銷毀。
getGhostName這在呼叫時出現在下面的行中il2cppi_to_string:
const char* name = il2cppi_to_string(ghostName).c_str();
我不完全確定這意味著什么或如何修改代碼來修復它。我絕對討厭在 C 中使用字串。
uj5u.com熱心網友回復:
il2cppi_to_string()回傳一個臨時 std::string的 ,它將在呼叫il2cppi_to_string(). 您正在獲取const char*指向該臨時 std::string資料的指標,這是 ReSharper 警告您的內容。由于臨時 std::string在 之前被銷毀return,這意味著getGhostName()回傳一個指向無效記憶體的懸空指標。
要解決此問題,請更改getGhostName()為回傳 astd::string而不是 a const char*:
std::string getGhostName(GhostAI* ghostAI)
{
if (ghostAI) {
GhostInfo* ghostInfo = getGhostInfo(ghostAI);
const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u0A68u0A74u0A6Au0A6F.u0A65u0A66u0A6Eu0A67u0A69u0A74u0A69u0A65u0A74u0A6Fu0A67;
return il2cppi_to_string(ghostName);
}
return "UNKNOWN";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/446143.html
