力为的技术博客

联系 聚合 管理
  154 Posts :: 1 Stories :: 561 Comments :: 0 Trackbacks

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

const   char *  pBuffer  =  oss.str().c_str();

pBuffer指向的内存已被析够!

测试代码:

        ostringstream oss;
        oss 
<<   " something you like "   <<  endl;

//  can't work!
         const   char *  szData1  =  oss.str().c_str();
        
// work!
         string &  ss  =  oss.str();
        
const   char *  szData2  =  ss.c_str();


例子:
用std::ostringstream获取整个文件的内容:

        ifstream ifs( " in.txt " );

        istream_iterator
< char >  inpos(ifs);
        istream_iterator
< char >  endpos;
        ostream_iterator
< char >   out (oss);
        std::copy(inpos, endpos, 
out );

// 有些情况下需要取得buffer:
         string &  ss  =  oss.str();
        
const   char *  szData  =  ss.c_str();


 

posted on 2006-06-08 16:49 力为 阅读(6403) 评论(5)  编辑 收藏 引用 所属分类: 4. C++ FAQ

评论

# re: std::ostringstream::str()返回临时对象 2006-06-08 17:26 LOGOS
const char * szData1 = oss.str().c_str();
szData1[0] == '\0';
不过既然是临时变量,你这么用
string & ss = oss.str();
const char * szData2 = ss.c_str();
不符合规范吧  回复  更多评论
  

# re: std::ostringstream::str()返回临时对象 2006-06-08 17:30 wzq
To LOGOS:
but it really works!  回复  更多评论
  

# re: std::ostringstream::str()返回临时对象 2006-06-08 17:48 力为
to LOGOS:
这种情况下编译器一般会做扩展:
为临时变量设置引用,那么临时变量的生命周期将和引用的生命周期一致  回复  更多评论
  

# re: std::ostringstream::str()返回临时对象 2006-06-12 21:41 ooo
// 有些情况下需要取得buffer:
string & ss = oss.str();
const char * szData = ss.c_str();

这是是不是该该成:
const string & ss = oss.str();
const char * szData = ss.c_str();

为临时变量设置引用,那么临时变量的生命周期将和引用的生命周期一致 ,
就应该加上 const, 可是在VC6.0上对这个语句string & ss = oss.str();且没有错误的提示.
  回复  更多评论
  

# re: std::ostringstream::str()返回临时对象 2006-12-13 10:26 jlupaopao
@ooo
g++下确实会有错误报告
error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >'

加上const就好了,其实加上const等同于
string temp =oss.str();
const string & ss = temp
const char * szData = ss.c_str();
既然如此为什么不直接写string ss =oss.str(); 呢
  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理