Returning 'c_str' from a function

后端 未结 4 1530
栀梦
栀梦 2020-12-03 18:34

This is from a small library that I found online:

const char* GetHandStateBrief(const PostFlopState* state)
{
    static std::ostringstream out;

    // ...          


        
4条回答
  •  旧巷少年郎
    2020-12-03 18:53

    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.

提交回复
热议问题