c_str使用不当 [英] Improper use of c_str
问题描述
我有一个定义如下的方法:
I have a method defined as below:
const std::string returnStringMethod()
{
std::string myString;
// populate myString
return myString;
}
现在,在呼叫者中,我正在执行以下操作:
Now, in the caller, I was doing something like this:
const char * ptr = returnStringMethod().c_str();
正如我所看到的,这将返回一些我没想到的截断的字符串.但是,以下方法可以正常工作:
As I can see this is returning some truncated string which I did not expect. However, the folllowing works fine:
std::string str = returnStringMethod();
const char * ptr = str.c_str();
有人可以帮助我了解这里发生的事情吗?
Can someone please help me understand whats happening here? .
PS:我们每周构建一次代码.上周提交代码时,我对此进行了测试,一切都很好.所以,我真的很想知道我在这里可能会缺少什么.
PS: We build code once a week. I tested this when I was submitting my code last week and things were fine. So, I really wanted to know what I might be missing here.
谢谢, 帕万.
推荐答案
第一个是未定义的行为,临时returnStringMethod()
仅在结尾的;
之前有效,因此内部字符串(由
The first is undefined behavior, the temporary returnStringMethod()
is valid only until the trailing ;
, so the internal string (returned by c_str()
) is destroyed, so you're left with a dangling pointer.
第二个版本有效,因为str
在其作用域结束时将被销毁,并且其作用域与ptr
相同(至少在您的示例中).
The second version is valid because str
will be destroyed when its scope ends, and its scope is the same as ptr
(at least in your example).
例如,以下内容也将是错误的:
For example, the following would also be wrong:
const char * ptr = NULL;
{
std::string str = returnStringMethod();
ptr = str.c_str();
}
}
之后,ptr
不再有效.
这篇关于c_str使用不当的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!