Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 was expecting the program to print:

Foo ABC

instead of

0x401bad ABC

Why 0x401bad ABC is printed?

g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
like image 544
Michal Avatar asked Feb 19 '15 16:02

Michal


1 Answers

operator<< is implemented in two parts:

  • Overloads for character data are free functions.
  • Other overloads are members of std::ostream.

We're concerned about the first one for that string literal. As you can see in the link, all of the overloads take a non-const reference to std::ostream. This means your temporary A() doesn't fit. Thus, the member function taking const void* is used.

C++11 adds support for an rvalue reference to std::ostream for a generic const T & argument, which accepts your temporary object, so the string literal is printed when compiling with C++11.

like image 86
chris Avatar answered Sep 23 '22 15:09

chris