子类化 stringstream 给出“0x401bad ABC”而不是 "Foo ABC"
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");
}
我期待程序打印:
Foo ABC
而不是
0x401bad ABC
为什么打印 0x401bad ABC?
g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
operator<<
分两部分实现:
- 字符数据重载是自由函数。
- 其他重载是
std::ostream
. 的成员
我们担心 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 正在使用 const void*
。
C++11 为通用 const T &
参数添加了对 std::ostream
右值引用的支持,该参数接受您的临时对象,因此在使用 C++11 编译时会打印字符串文字.
#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");
}
我期待程序打印:
Foo ABC
而不是
0x401bad ABC
为什么打印 0x401bad ABC?
g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
operator<<
分两部分实现:
- 字符数据重载是自由函数。
- 其他重载是
std::ostream
. 的成员
我们担心 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 正在使用 const void*
。
C++11 为通用 const T &
参数添加了对 std::ostream
右值引用的支持,该参数接受您的临时对象,因此在使用 C++11 编译时会打印字符串文字.