Tag: c str

从函数返回’c_str’

这是我在网上找到的一个小型图书馆: const char* GetHandStateBrief(const PostFlopState* state) { static std::ostringstream out; // … rest of the function … return out.str().c_str() } 在我的代码中,我这样做: const char *d = GetHandStateBrief(&post); std::cout<< d << std::endl; 现在,起初d包含垃圾。 然后我意识到,当函数返回时,我从函数中获取的C字符串被销毁,因为在堆栈上分配了std::ostringstream 。 所以我补充说: return strdup( out.str().c_str()); 现在我可以从函数中获取我需要的文本。 我有两个问题: 我理解正确吗? 后来我注意到out (类型为std::ostringstream )分配了静态存储。 这是不是意味着在程序终止之前该对象应该留在内存中? 如果是这样,那为什么不能访问该字符串?