如何返回std :: string.c_str() [英] How to return a std::string.c_str()

查看:432
本文介绍了如何返回std :: string.c_str()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回常量char指针的方法.它使用std::string并最终返回其c_str() char指针.

I have a method which returns the constant char pointer. It makes use of a std::string and finally returns its c_str() char pointer.

const char * returnCharPtr()
{
    std::string someString;

    // some processing!.

    return someString.c_str();
}

我从COVERITY工具得到了一个报告,上面的用法不是很好.我用Google搜索,发现返回的char指针在someString遇到销毁时将立即失效.

I have got a report from COVERITY tool that the above is not a good usage. I have googled and have found that the char pointer returned, would be invalidated as soon as someString meets its destruction.

鉴于此,如何解决此问题?如何准确返回char指针?

Given this, how does one fix this issue? How to return char pointer accurately?

返回std::string将解决此问题.但是我想知道是否还有其他方法可以做到这一点.

Returning std::string would resolve this issue. But I want to know if there is any other means of doing this.

推荐答案

此代码中发生的事情是:

What happens in this code is:

const char * returnCharPtr()
{
    std::string someString("something");
    return someString.c_str();
}

  1. std::string的实例已创建-它是具有自动存储期限的对象
  2. 返回指向该字符串的内部存储器的指针
  3. 对象someString被破坏,其内部存储器被清理
  4. 此函数的调用者收到 悬挂指针 (无效指针),该指针会产生 未定义行为
  1. instance of std::string is created - it is an object with automatic storage duration
  2. pointer to the internal memory of this string is returned
  3. object someString is destructed and the its internal memory is cleaned up
  4. caller of this function receives dangling pointer (invalid pointer) which yields undefined behavior

最佳解决方案:返回对象:

std::string returnString()
{
    std::string someString("something");
    return someString;
}

这篇关于如何返回std :: string.c_str()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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