c++ - Why does writing into temporary string stream object only print object addresses? -


the following snippet simplified version of logger use. extends std::ostringstream , can filled using <<-operator. upon destruction content written std::cout.

writing (<<) directly temporary object, logger(), expect print input, however, prints address of on std::cout. when writing reference of temporary object, logger().stream(), works expected.

why happening?

btw, behavior occurs in c++98-land (ideone), have use. c++11 (coliru) , c++14 (ideone) both call variants work expected. what's different in c++11/14?

#include <iostream> #include <sstream>  class logger : public std::ostringstream { public:     ~logger()     {         std::cout << this->str() << std::endl;     }      logger& stream()     {         return *this;     } };  int main( int argc, char ** argv ) {     // 1.     // prints address, e.g. 0x106e89d5c.     logger() << "foo";      // 2.     // works expected.     logger().stream() << "foo";      // difference between 1. , 2.?      return 0; } 

the operator<< handles insertion of const char * non-member template:

template< class traits >  basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& os, const char* s); 

it takes stream non-const (lvalue) reference, not bind temporaries.

in c++98/03, best viable function member operator<<(const void *), prints address.

in c++11 , later, library supplies special operator<< rvalue streams:

template< class chart, class traits, class t > basic_ostream< chart, traits >& operator<<( basic_ostream<chart,traits>&& os,                                              const t& value ); 

which os << value , returns os, performing output operation on lvalue stream.


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -