std::ostringstream::str()返回临时对象

时间:2022-06-08 02:16:36

取得std::ostringstream里的内容可以通过str()和str(string&)成员函数。由于str()返回的是临时对象,因而会有如下误用:

std::ostringstream::str()返回临时对象const   char   *   pBuffer  =   oss.str().c_str();

pBuffer指向的内存已被析够!
测试代码:

std::ostringstream::str()返回临时对象ostringstream oss;
std::ostringstream::str()返回临时对象        oss 
<<   " something you like "   <<   endl;
std::ostringstream::str()返回临时对象 
std::ostringstream::str()返回临时对象 
//   can't work!
std::ostringstream::str()返回临时对象
  const   char   *   szData1  =   oss.str().c_str();
std::ostringstream::str()返回临时对象 
std::ostringstream::str()返回临时对象 
// work!
std::ostringstream::str()返回临时对象
std::string   ss  =   oss.str();
std::ostringstream::str()返回临时对象 
const   char   *   szData2  =   ss.c_str();
std::ostringstream::str()返回临时对象

例子:
用std::ostringstream获取整个文件的内容:std::ostringstream::str()返回临时对象        

std::ostringstream::str()返回临时对象ifstream ifs( " in.txt " );
std::ostringstream::str()返回临时对象 
std::ostringstream::str()返回临时对象        istream_iterator
<   char   >   inpos(ifs);
std::ostringstream::str()返回临时对象        istream_iterator
<   char   >   endpos;
std::ostringstream::str()返回临时对象        ostream_iterator
<   char   >   out (oss);
std::ostringstream::str()返回临时对象        std::copy(inpos, endpos, 
out );
std::ostringstream::str()返回临时对象 
std::ostringstream::str()返回临时对象 
// 有些情况下需要取得buffer:
std::ostringstream::str()返回临时对象
std::string   ss  =   oss.str();
std::ostringstream::str()返回临时对象 
const   char   *   szData  =   ss.c_str();