What is the most efficient way to implement returned computed value in C ++?

With rvalue references appearing at the top of Return Value Optimization, what would be the most efficient way to implement such a core function? How can I improve this implementation or leave it alone?

template <typename T>
string
to_string(const T& t)
{ 
  stringstream ss;
  ss << t;  
  return ss.str();
} 

Obviously, I want to avoid copying or allocating memory if I can. TIA.

Edit: from thanks to D. Rodriguez for this detailed answer. Now I have the second part of my question. Is there any way to improve this?

#define to_cstr( T ) (to_string( T ).c_str())

Of course, I would like to avoid MACROs if I can, but if I copy and paste the template code above to return ss.str (). c_str () and const char *, temporary does not live long enough; although the code seems to work, valgrind complains (red light).

, MACRO to_cstr(). , , ?

+5
2

, , . ++ 03 .

, to_string, return to_string return ss.str() . , , , .

return, , 32/64, ( VS, gcc, intel, suncc), , , - :

// Not valid C++! Just for illustration purposes
template <typename T>
to_string( uninitialized<string>* res, const T& t ) {
   stringstream ss;
   ss << t;
   stringstream::str( res, &ss ); // first argument is return location
                                  // second argument is `this`
}
+7

. ?

#define to_cstr( T ) (to_string( T ).c_str())

, MACROs, , , ss.str(). c_str() const char *, ; , , , valgrind ( ).

, , . :

struct TmpStr {
    mutable std::string s;
};

template<typename T>
char const* to_cstr(T value, TmpStr const& tmp = TmpStr()) {
    tmp.s = to_string(value); // your original function
    return tmp.s.c_str(); // tmp lives in the scope of the caller
}

int main() {
    printf("%s\n", to_cstr(1));
}
0

All Articles