问题描述
我有一个函数,返回一个字符串。然而,当我调用它,并做它的c_str()它转换成一个const char *,它只有当我把它存储到另一个字符串首先工作。如果我直接调用c_str()函数,它将垃圾值存储在const char *中。
I have a function that is returning a string. However, when I call it and do c_str() on it to convert it into a const char*, it only works when I store it into another string first. If I directly call c_str() off of the function, it stores garbage value in the const char*.
为什么会发生这种情况?感觉我在这里缺少一些非常根本的东西...
Why is this happening? Feel like I'm missing something very fundamental here...
SomeFunction().c_str() gives you a pointer to a temporary(the automatic variable str in the body of SomeFunction). Unlike with references, the lifetime of temporaries isn't extended in this case and you end up with charArray being a dangling pointer explaining the garbage value you see later on when you try to use charArray.
另一方面,当您执行
string str_copy = SomeFunction();str_copy 是返回值的副本 SomeFunction()。现在调用 c_str(),可以指向有效数据。
str_copy is a copy of the return value of SomeFunction(). Calling c_str() on it now gives you a pointer to valid data.
这篇关于为什么在返回字符串的函数上调用c_str()不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!