http://blog./xman/43212.html GetBuffer()主要作用是將字符串的緩沖區(qū)長度鎖定,releaseBuffer則是解除鎖定,使得CString對象在以后的代碼中繼續(xù)可以實(shí)現(xiàn)長度自適應(yīng)增長的功能。 CString ::GetBuffer有兩個(gè)重載版本: LPTSTR GetBuffer( );LPTSTR GetBuffer(int nMinBufferLength); 在第二個(gè)版本中,當(dāng)設(shè)定的長度小于原字符串長度時(shí),nMinBufLength = nOldLen,該參數(shù)會被忽 略,不分配內(nèi)存,指向原CString;當(dāng)設(shè)定的長度大于原字符串本身的長度時(shí)就要重新分配(reallocate)一塊比較大的空間出來。而調(diào)用第一個(gè)版本時(shí),應(yīng)如通過傳入0來調(diào)用第二個(gè)版本一樣。 是否需要在GetBufer后面調(diào)用ReleaseBuffer(),是根據(jù)你的后面的程序是否需要繼續(xù)使用該字符串變量,并且是否動(dòng)態(tài)改變其長度而定的。如果你GetBuffer以后程序自函數(shù)就退出,局部變量都不存在了,調(diào)用不調(diào)用ReleaseBuffer沒什么意義了。 這是一個(gè)非常容易被用錯(cuò)的函數(shù),主要可能是由于大家對它的功能不太了解。其實(shí)點(diǎn)破的話,也不是那么深?yuàn)W。
補(bǔ)充一下: GetBuffer說白了就兩個(gè)功能: 1:就是將CString里面的內(nèi)存交到外部一個(gè)來處理,外部可以直接修改它的內(nèi)容。 2:重新修改CString的內(nèi)存大小,這個(gè)數(shù)值不包含null結(jié)尾符。 另一個(gè)典型的用法:就是將CString里面的內(nèi)容變?yōu)閕nt或long型,需要先獲取里面的內(nèi)存指針。這樣就可以先GetBuffer(內(nèi)存大?。┓奖阒苯愚D(zhuǎn)換。 如果在外部修改了CString里面的內(nèi)容,在重新使用CString之前,需調(diào)用ReleaseBuffer()也就是說,ReleaseBuffer不需要每次都調(diào)用。 MSDN原文: If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CSimpleStringT member methods. The buffer memory is automatically freed when the CSimpleStringT object is destroyed. 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 (the default) for the length to ReleaseBuffer, and ReleaseBuffer will perform a strlen on the buffer to determine its length. |
|