CString的局部变量使用GetBuffer
是否一定要使用ReleaseBuffer呢?

解决方案 »

  1.   

    通过GetBuffer得到的指针对字符串进行修改后就要释放.
      

  2.   

    在大多数情况下,应使用 CString 成员函数来修改 CString 对象的内容或将 CString 转换为一个 C 样式的字符串。但是,在某些情况下,比如使用需要字符缓冲区的操作系统函数,直接修改 CString 内容是较为有利的。GetBuffer 和 ReleaseBuffer 成员函数使您能够访问 CString 对象的内部字符缓冲区,并直接进行修改。以下步骤显示如何使用这些函数来达到这一目的: 为 CString 对象调用 GetBuffer,并指定所需缓冲区的长度。 
    使用由 GetBuffer 返回的指针来直接将字符写入 CString 对象中。 
    调用 CString 对象的 ReleaseBuffer 来更新所有的内部 CString 状态信息,如字符串的长度。直接修改完 CString 对象的内容之后,在调用任何其他 CString 成员函数之前必须调用 ReleaseBuffer。 
      

  3.   

    作为良好的编程风格和习惯,在使用GetBuffer后,一定要ReleaseBuffer
      

  4.   

    推荐还是使用GetBuffer后,一定要ReleaseBuffer虽然有时候不会错。但是 一个大的工程 也许就在这些地方出了问题。良好的编程风格还是很有必要的
      

  5.   

    一定要用 我曾经遇到过这个问题
    当时 字符串怎么都该不了了 
    releasebuffer之后就好了
      

  6.   

    一定要,GetBuffer会调用LockBuffer的,
      

  7.   

    一帮人说了半天也没说到点子上。
    GetBuffer()主要作用是将字符串的缓冲区长度锁定,releaseBuffer则是解除锁定,使得CString对象在以后的代码中继续可以实现长度自适应增长的功能。是否需要在GetBufer后面调用ReleaseBuffer(),是根据你的后面的程序是否需要继续使用该字符串变量,并且是否动态改变其长度而定的。不是什么好地编程习惯,之类的原因。
    如果你GetBuffer以后程序自函数就退出,局部变量都不存在了,调用不掉用ReleaseBuffer没什么意义了。但如果你出现例如下面的代码
    CString m_strA;
    m_strA=_T("123456");
    m_strA.GetBuffer(6);
    m_strA+=_T("789");//此时就会出错了,因为需要动态加长字符串长度
      

  8.   

    早上看MSDN时,上面说:
    If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.The address returned by GetBuffer may not be valid after the call to ReleaseBuffer since additional CString operations may cause the CString buffer to be reallocated. The buffer will not be reallocated if you do not change the length of the CString.The buffer memory will be freed automatically when the CString object is destroyed. Note that if you keep track of the string length yourself, you should not append the terminating null character. You must, however, specify the final string length when you release the buffer with ReleaseBuffer. If you do append a terminating null character, you should pass –1 for the length to ReleaseBuffer and ReleaseBuffer will perform a strlen on the buffer to determine its length. 
      

  9.   

    学习啦,gaohl回答的很透彻!谢谢!
      

  10.   

    学习了,原来GetBuffer会调用LockBuffer的,我说怎么老是报错。
      

  11.   

    不是风格的问题,局部变量如果用完当前对象就消除了,或者看这个字符串是否以后要改变其长短大小,才决定使用getBuffer()