use*_*421 8 c c++ c-strings c-str static-allocation
这是我在网上找到的一个小型图书馆:
const char* GetHandStateBrief(const PostFlopState* state)
{
static std::ostringstream out;
// ... rest of the function ...
return out.str().c_str()
}
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我这样做:
const char *d = GetHandStateBrief(&post);
std::cout<< d << std::endl;
Run Code Online (Sandbox Code Playgroud)
现在,起初d包含垃圾.然后我意识到,当函数返回时,我从函数中获取的C字符串将被销毁,因为它std::ostringstream是在堆栈上分配的.所以我补充说:
return strdup( out.str().c_str());
Run Code Online (Sandbox Code Playgroud)
现在我可以从函数中获取我需要的文本.
我有两个问题:
我理解正确吗?
后来我注意到out(类型std::ostringstream)分配了静态存储.这是不是意味着在程序终止之前该对象应该留在内存中?如果是这样,为什么不能访问该字符串?
Mar*_*tos 11
strdup在堆上分配一个字符串的副本,你必须稍后手动释放(free()我认为).如果您有选择权,那么返回会更好std::string.
静态存储out没有帮助,因为.str()返回一个临时的std::string,当函数退出时会被破坏.