Re: [cpp] 如何优雅地获取string 对象的可写缓冲区

qiaojie qiaojie at gmail.com
Tue Nov 14 13:53:11 CST 2006


string当然要保证内存是连续的,不然c_str()就错了。
string是最不实用的string类,我宁可用ATL的CString。


在06-11-14,Alized <bluecjq at gmail.com> 写道:
>
> 标准没有保证string里的数据是分配在一块连续的区域的,这样做依赖与库的实现,不具可移植性。
>
> 在06-11-14,j9803 <j9803 at 163.com> 写道:
> >
> >  直接访问 str.begin() 就可以了
> >
> >  ----- Original Message -----
> > *From:* Lingoes <lingoes at gmail.com>
> > *To:* cpp at codingnow.com
> > *Sent:* Sunday, November 12, 2006 9:29 PM
> > *Subject:* [cpp] 如何优雅地获取string 对象的可写缓冲区
> >
> >
> > 大家知道 c++ string 对象仅提供了 const char* c_str() 方法来直接访问数据缓冲区,
> > 但在实际应用中, 经常需要从string 中得到数据缓冲区的可写指针, 直接写入数据, 以加快程序的性能.
> > 由于string 的引用计数机制 (vc6), 直接强制转换 char *buf = (char *)string.c_str() 是不可行的,
> >
> > 我通常会采用以下的技巧:
> >
> > string str, str2;
> > str = "abcde".
> > str2 = str;
> > ...
> > // 断开引用计数
> > char& c0 = str.at(0);
> > // 取可写指针
> > char *buf = &c0;
> >
> > 这个方法非常有效 (VC6下), 但太过于依赖于标准库的内部实现, 不知道大家有没有更优雅通用的方法来实现它呢?
> >
> >
> >
> > ------------------------------
> >
> > _______________________________________________
> > Cpp mailing list
> > Cpp at codingnow.com
> > http://codingnow.com/mailman/listinfo/cpp
> >
> >
> > _______________________________________________
> > Cpp mailing list
> > Cpp at codingnow.com
> > http://codingnow.com/mailman/listinfo/cpp
> >
> >
>
> _______________________________________________
> Cpp mailing list
> Cpp at codingnow.com
> http://codingnow.com/mailman/listinfo/cpp
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://codingnow.com/pipermail/cpp/attachments/20061114/312a52f9/attachment.html


More information about the Cpp mailing list