Subclassing stringstream gives "0x401bad ABC" instead of "Foo ABC"
#include <sstream> #include <iostream> #include <string> class A : public std::stringstream { public: A() {} ~A() { std::cout << str().c_str() << std::endl; } }; int main() { A() << "Foo" << std::string(" ABC"); } I expected the program to be printed:
Foo ABC instead
0x401bad ABC Why is 0x401bad ABC printed?
g++ --version g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 operator<< is implemented in two parts:
- Overloads for character data are free features.
- Other overloads are members of
std::ostream.
We are first concerned for this string literal. As you can see in the link, all overloads accept a non-constant link to std::ostream . This means that your temporary A() not suitable. Thus, the member function is used, which takes const void* .
C ++ 11 adds support for the rvalue reference to std::ostream for the generic const T & argument, which takes your temporary object, so the string literal is printed when compiling with C ++ 11.