8

这是我在网上找到的一个小型图书馆:

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());

现在我可以从函数中获取我需要的文本。

我有两个问题:

  1. 我是否正确理解这一点?

  2. 后来我注意到out(类型std::ostringstream)被分配了静态存储。这是否意味着该对象应该保留在内存中直到程序终止?如果是这样,那为什么不能访问字符串?

4

4 回答 4

11

strdup allocates a copy of the string on the heap, which you have to free manually later (with free() I think). If you have the option, it would be much better to return std::string.

The static storage of out doesn't help, because .str() returns a temporary std::string, which is destroyed when the function exits.

于 2010-04-17T04:06:06.960 回答
3

You're right that out is a static variable allocated on the data segment. But out.str() is a temporary allocated on the stack. So when you do return out.str().c_str() you're returning a pointer to a stack temporary's internal data. Note that even if a string is not a stack variable, c_str is "only granted to remain unchanged until the next call to a non-constant member function of the string object."

I think you've hit on a reasonable workaround, assuming you can't just return a string.

于 2010-04-17T04:12:54.470 回答
0

strdup() returns a char* pointer that is pointing to memory on the heap. You need to free() it when you're done with it, but yes, that will work.

The static local variable std::ostringstream out makes no sense in this case, unless the std::string being returned was also static which your observation is showing to be not true.

于 2010-04-17T04:12:38.100 回答
-1

In GetHandStateBrief, variable out does not need to be static. You need an explicit static string to replace the temporary that was being created in your original call to out.str():

static std::string outStr;
std::ostringstream out;
... rest of function ...
outStr = out.str();
return outStr.c_str();
于 2010-04-17T04:08:15.520 回答