Why is recording in a temporary stream not performed?

Consider the following code:

#include <sstream> #include <iostream> class Foo : public std::stringstream { public: ~Foo() { std::cout << str(); } }; int main() { Foo foo; foo << "Test1" << std::endl; Foo() << "Test2" << std::endl; return 0; } 

When I do this, he gives me:

 004177FC Test1 

I do not understand why the second example gives me gibberish. The temporary should live until the whole expression is evaluated, so why doesn't it behave the same as in the first example?

+7
source share
1 answer

I tested it.

I can guess that operator<< cannot bind a temporary to a non-constant reference, so any externally defined operator <<functions will not work on a temporary Foo, but any members of the class will do so if ostream or ostringstream have any internal members of operator<< which they will work.

Therefore, it may be that overloading the pointer is a member function, while special for const char * is externally declared.

A non-temporary can be associated with a non-constant reference for a more specialized overload.

If you really need it, you can bypass the shell

 class Foo : { mutable std::ostringstream oss; public: ~Foo() { std::cout << oss.str(); } template<typename T> std::ostream& operator<<( const T& t ) const { return oss << t; } }; 

Tested and working. The first operator <will return the base stream to you.

I tried this too, but this has been fixed:

 class Foo : std::ostringstream { Foo & nonconstref; public: Foo() : nonconstref( *this ) {} ~Foo() { std::cout << str(); } template<typename T> std::ostream& operator<<( const T& t ) const { return nonconstref << t; } }; 

This also works:

 class Foo : public std::ostringstream { public: Foo() {} ~Foo() { std::cout << str(); } Foo& ncref() { return *this; } }; int main() { Foo foo; foo << "Test1" << std::endl; Foo().ncref() << "Test2" << std::endl; } 
+7
source

All Articles