如何返回std :: string.c_str() [英] How to return a 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();
}
-
std::string
的实例已创建-它是具有自动存储期限的对象 - 返回指向该字符串的内部存储器的指针
- 对象
someString
被破坏,其内部存储器被清理 - 此函数的调用者收到 悬挂指针 (无效指针),该指针会产生 未定义行为
- instance of
std::string
is created - it is an object with automatic storage duration - pointer to the internal memory of this string is returned
- object
someString
is destructed and the its internal memory is cleaned up - 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屋!