将C弦发送到非效果STD :: OSTRINGSTREAM怪异行为

sending c-string to non-lvalue std::ostringstream weird behaviour

本文关键字:OSTRINGSTREAM STD      更新时间:2023-10-16

测试代码:

#include <iostream>
#include <sstream>
int main() {
  std::ostringstream q;
  std::cout << (dynamic_cast<std::ostringstream&>(q<<"hello"<<101).str()) << "n";
  std::cout << (dynamic_cast<std::ostringstream&>(std::ostringstream()<<"hello"<<101).str()) << "n";
  return 0;
}

用:g test.cpp编译输出:

hello101
hello101

编译:G -std = C 98 Test.cpp输出:

hello101
0x4b2ec0101

看起来第二个字符串包含指向字符串本身的" Hello"字符串的指针。为什么?是GCC中的C 98标准或错误的某些"功能"?

在C 03中,非成员operator<<(源(,负责打印C字符串,即

template< class Traits >
basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os,  
                                        const char* s );

无法接受rvalue流,因此选择了成员过载(从std::ostream基类继承((来源(:

basic_ostream& operator<<( const void* value );

这打印出地址。

在C 11中,有一个RVALUE流插入操作员,

template< class CharT, class Traits, class T >
basic_ostream< CharT, Traits >& operator<<( basic_ostream<CharT,Traits>&& os, 
                                            const T& value );

确保LVALUE和RVALUE流的行为将相同。请注意,此过载不可能写在C 03中,因为绑定到RVALUE的唯一方法是通过const lvalue参考。