我有一个返回常量字符指针的方法.它使用 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();
}
std::string
的实例被创建 - 它是一个具有自动存储持续时间的对象someString
被销毁并清理其内部内存std::string
is created - it is an object with automatic storage durationsomeString
is destructed and the its internal memory is cleaned up最好的解决方案是返回一个对象:
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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!