0

I'm writing the following functions intending to return a copy of a stringstream object. func_A serves as a C wrap for some C++ functions. So the return value has to be char* or const char* for func_B() and main to use.

When func_A is called I do see the printed out string, but I can not return the result_string. After some googling I found out that you can not copy the result of stringstream at all. I changed the return as result_string.str().c_str() hoping that is can return a string. But that does not seem to work either. Any suggestions to how I can return a copy of the result_string? For example, is there a way I can read the stringsteam content and record it in a buffer?

    const char* func_A(char* A, char* B, char* C){
        // processing the string
        // ...
        std::stringstream result_string;
        result_string << paramA << ":" 
                 << paramB << ":" 
                 << paramC;

        // return the result string
        printf("%s\n", result_string.str().c_str()); 
        return result_string.str().c_str();
    }

    const char* func_B(){
        ...
        ...
        return func_A(A, B, C);
    }

    int main(){
        ...
        ...
        const char* buff = func_B();
        printf("This is the content: %s", buff);
        free(buff);
    }
DavidKanes
  • 183
  • 1
  • 1
  • 10
  • I'm not sure I follow. Do you mean something like [this](https://godbolt.org/z/d6q51xsxE)? Why are you mixing `const char*`s and `printf()` into this? It just makes it harder. – Ted Lyngmo Jun 22 '21 at 21:52
  • 1
    You _can_ use str(). What source told you that you cannot use it? – tobias Jun 22 '21 at 21:52
  • 2
    Never, ever, return a pointer or a reference to a non-static object that was created in function. All non-statics are destroyed when the function ends. – NathanOliver Jun 22 '21 at 21:54
  • 3
    You can't return `result_string.str().c_str()` because that is a pointer to a temporary string created from a local stringstream which gets deallocated when the function returns. To return a pointer tou need to malloc memory and strcpy the `result_string.str().c_str()` into it - that's the only way it will outlive the end of the function (or you could pass in the stringstream so that it exists outside the function - then when you return a pointer to the contents of the stringstream it will point to an object that still exists) – Jerry Jeremiah Jun 22 '21 at 21:56
  • 1
    _" I found out that you can not copy the result of stringstream at all."_ The result of your stringstream is available via `result_string.str()`. It's a `std::string` and you certainly **can** copy it. I suspect that you were trying to _copy the stream itself_ and not the resulting string. I'm voting to close this as a typo. – Drew Dormann Jun 22 '21 at 22:07

0 Answers0