#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
operator<<
is implemented in two parts:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With