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

Lingoes lingoes at gmail.com
Sun Nov 12 21:29:45 CST 2006


大家知道 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下), 但太过于依赖于标准库的内部实现, 不知道大家有没有更优雅通用的方法来实现它呢?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://codingnow.com/pipermail/cpp/attachments/20061112/87a4fdf2/attachment.html


More information about the Cpp mailing list