c++ - Odd(?) behaviour of a temporary std::ostringstream -


i messing around std::ostringstream whilst looking @ question: sprintf in c++?, , noticed stringbuilder() wrapper nawaz , thought, ought work std::ostringstream.

so first attempt following:

std::cout << (std::ostringstream("select * foo limit") << max_limit).str() << std::endl; 

now fails compile (correctly) result of operator<< std::ostream - doesn't have member str(). thought cast should trick, , cast const reference (works cast normal reference too), second attempt:

std::cout << static_cast<std::ostringstream const&>(std::ostringstream("select * foo limit") << max_limit).str() << std::endl; 

now compiles fine , runs, output is, well, not expecting.

10lect * foo limit

now - here's question, invoking undefined behaviour somewhere - , if where? , how different approach nawaz has taken (i guess aside result of operator stringbuilder rather std::ostream).

edit: here ideone code.

edit: oops - forgot specify, max_limit int.

you need move stream's position end of internal buffer used ostringstream:

  std::ostringstream out("select * foo limit ", std::ios_base::app);   out << max_limit;   std::cout << out.str () << std::endl; 

see documentation on ostringstream constructor.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -