我有一个返回字符串的函数.但是,当我调用它并对其执行c_str()以将其转换为const char*时,它仅在我首先将其存储到另一个字符串时才起作用.如果我直接从函数中调用c_str(),它会将垃圾值存储在const char*中.
为什么会这样?感觉我在这里遗漏了一些非常基本的东西......
string str = SomeFunction();
const char* strConverted = str.c_str(); // strConverted stores the value of the string properly
const char* charArray= SomeFunction().c_str(); // charArray stores garbage value
static string SomeFunction()
{
string str;
// does some string stuff
return str;
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*han 22
SomeFunction().c_str()给你一个临时指针(str体内的自动变量SomeFunction).不像引用临时对象的生命周期在这种情况下不延长,你最终charArray是一个悬摆指针解释你看到的垃圾值后来当您尝试使用charArray.
另一方面,当你这样做
string str_copy = SomeFunction();
Run Code Online (Sandbox Code Playgroud)
str_copy是一个返回值的副本SomeFunction().c_str()现在调用它会为您提供指向有效数据的指针.