Search code examples
c++doublestdstringmemory-efficient

Converting double to string function - memory issues?


I find myself having to std::cout various double variables. I've made a simple function to convert a double to a std::string, which I can then use with std::cout etc.

// Convert a double to a string.
std::string dtos(double x) {
    std::stringstream s;
    s << x;
    return s.str();
}

The function seems to work OK, but my question is: does this approach have any (bad) memory implications ie. am I allocating unecessary memory, or leaving anything 'dangling'?

Thanks guys Pete


Solution

  • No, your code is OK, read the comments on the code:

    std::string dtos(double x) {
        std::stringstream s;  // Allocates memory on stack
        s << x;
        return s.str();       // returns a s.str() as a string by value
                              // Frees allocated memory of s
    } 
    

    In addition, you can pass a double to cout directly.