|
http://blog./xman/43212.html GetBuffer()主要作用是將字符串的緩沖區(qū)長度鎖定,releaseBuffer則是解除鎖定,使得CString對象在以后的代碼中繼續(xù)可以實現(xiàn)長度自適應增長的功能。 CString ::GetBuffer有兩個重載版本: LPTSTR GetBuffer( );LPTSTR GetBuffer(int nMinBufferLength); 在第二個版本中,當設定的長度小于原字符串長度時,nMinBufLength = nOldLen,該參數(shù)會被忽 略,不分配內(nèi)存,指向原CString;當設定的長度大于原字符串本身的長度時就要重新分配(reallocate)一塊比較大的空間出來。而調(diào)用第一個版本時,應如通過傳入0來調(diào)用第二個版本一樣。 是否需要在GetBufer后面調(diào)用ReleaseBuffer(),是根據(jù)你的后面的程序是否需要繼續(xù)使用該字符串變量,并且是否動態(tài)改變其長度而定的。如果你GetBuffer以后程序自函數(shù)就退出,局部變量都不存在了,調(diào)用不調(diào)用ReleaseBuffer沒什么意義了。 這是一個非常容易被用錯的函數(shù),主要可能是由于大家對它的功能不太了解。其實點破的話,也不是那么深奧。
補充一下: GetBuffer說白了就兩個功能: 1:就是將CString里面的內(nèi)存交到外部一個來處理,外部可以直接修改它的內(nèi)容。 2:重新修改CString的內(nèi)存大小,這個數(shù)值不包含null結尾符。 另一個典型的用法:就是將CString里面的內(nèi)容變?yōu)閕nt或long型,需要先獲取里面的內(nèi)存指針。這樣就可以先GetBuffer(內(nèi)存大小)方便直接轉換。 如果在外部修改了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. |
|
|
來自: semo_zhang > 《vc 》