如何返回 std::string.c_str()

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

问题描述

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

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 工具那里得到了一个报告,上面提到的不是一个好的用法.我用谷歌搜索并发现返回的字符指针会在 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.

推荐答案

这段代码发生了什么:

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

  1. std::string 的实例被创建 - 它是一个具有自动存储持续时间的对象
  2. 返回指向该字符串内部存储器的指针
  3. object 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;
}

在调用您的函数时,不要这样做:

When calling your function, DO NOT do this:

const char *returnedString = returnString().c_str();

因为在返回的std::string被销毁后,returnedString仍然是dangling.而是存储整个 std::string:

because returnedString will still be dangling after the returned std::string is destructed. Instead store the entire std::string:

std::string returnedString = returnString();
// ... use returnedString.c_str() later ...

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
Math-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)