Ostringstream
Output stream class to operate on strings.
Std
The C++ Standard Library, and its namespace
Others
Example |
---|
In c++ you could associate the output stream with a null device too and test the number of charactes printed with std ostream tellp;however using ostringstream is a way better solution see the answers by devsolar or angew from question Using sprintf with std::string in C++ |
Olding a lock while logging isn t great for performance although t s better than your existing log method which should use std lock_guard for exception safety;building and discarding a temporary ostringstream is probably better but if you care about performance you ll need to benchmark and may well end up requiring something more elaborate per-thread circular buffers mmapped files or something from question Writing a simple C++ thread safe logging lib, how to make thread safe << operator? |
Oss.clear here is the code here are the results now using std string is still faster and the append is still the fastest way of concatenation but ostringstream is no more so incredibly terrible like it was before from question Most optimized way of concatenation in strings |
However i don t know if use a std ostringstream is better than std string append so as you can see i used std sregex_iterator instead of std sregex_token_iterator from question Regex replace with callback in c++11? |
Edited since you chose the second approach i would recommend using std ostringstream than sprintf and using cclog instead of outputdebugstring because you just print std ostringstream out and independent os no need extra arguments from question How to print a two dimensional array in cocos2dx |
Std ostringstream has certainly better properties regarding memory safety as snprintf has better properties over sprintf . from question Convert Double to Hex String? |
By returning a std basic_stringbuf it s easy to see that std ostringstream uses a stringbuf internally and std ostringstream also provides easier access to the str functions of std basic_stringbuf functions which doesn t exist in std basic_streambuf from question Is it possible to change ostringstream rdbuf? |
On ideone the ostringstream is about 3 times slower than std copy + back_inserter + std vector and about 15 times slower than memcpy into a raw buffer from question Does the C++ standard mandate poor performance for iostreams, or am I just dealing with a poor implementation? |
Std ostringstream s more convenient and safer than std ostrstream because std ostringstream manages all memory automatically so you don t need to call freeze false to ensure the memory gets freed when you re finished with the memory from question What should I use instead of std::ostrstream? |
However std ostringstream is probably faster for appending if you absolutely have no idea about the size you have to reserve from question C++ std::ostringstream vs std::string::append |