c_str使用不当 [英] Improper use of c_str

查看:99
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆