CString GetBuffer() and ReleaseBuffer()

CString GetBuffer() and ReleaseBuffer()
2009-05-12 16:32

原文地址:http://hi.baidu.com/winnyang/blog/item/067b0a5423805f173b293508.html

LPTSTR GetBuffer( int nMinBufLength ) 這個函數是CString 的一個比較實用的函數,請看如下示例:

GetBuffer(int nMinBufLength);的參數問題一直比較困擾人,網站的資料還像也不是太好給的,請看msdn解釋

Parameters
nMinBufLength
The minimum size of the character buffer in characters. This value does not include space for a null terminator.
得到buffer的最小長度,當然這是由我們自己設定的一個參數,其原型定義如下:
LPTSTR CString::GetBuffer(int nMinBufLength)
{
ASSERT(nMinBufLength >= 0);

if (GetData()->nRefs > 1 || nMinBufLength > GetData()->nAllocLength)
{
#ifdef _DEBUG
   // give a warning in case locked string becomes unlocked
   if (GetData() != _afxDataNil && GetData()->nRefs < 0)
    TRACE0("Warning: GetBuffer on locked CString creates unlocked CString!/n");
#endif
   // we have to grow the buffer
   CStringData* pOldData = GetData();
   int nOldLen = GetData()->nDataLength;   // AllocBuffer will tromp it
   if (nMinBufLength < nOldLen)
    nMinBufLength = nOldLen;
   AllocBuffer(nMinBufLength);
   memcpy(m_pchData, pOldData->data(), (nOldLen+1)*sizeof(TCHAR));
   GetData()->nDataLength = nOldLen;
   CString::Release(pOldData);
}
ASSERT(GetData()->nRefs <= 1);

// return a pointer to the character storage for this string
ASSERT(m_pchData != NULL);
return m_pchData;
}

上面的代碼已經比較清楚了,當設定的長度小於原字符串長度時,nMinBufLength = nOldLen,然後分配相應的內存,當你設定的長度大於原字符串本身的長度時就要分配一塊比較大的空間出來,這時你可以實現字符串對接的操作,請看如下一段代碼:

CString s;
s
= " abc "
;
char * p = s.GetBuffer( 6
);
  
int l =
s.GetLength();
memcpy(p
+ l, " 111 " , 3
);
char * c = new char [ 6
];
memset(c,
' 1 ' , 3
);
char * d = " sss "
;
strcat(c,d);
CString e;
e
=
(LPCTSTR)c;
AfxMessageBox(e);
AfxMessageBox(s);

s.ReleaseBuffer();  
// Surplus memory released, p is now invalid.



這段代碼主要是考察GetBuffer()函數的動作,在char* p=s.GetBuffer(6),通過debug 可以看到p[6]='',這說明他自動加上了一個結束符,如果你分配空間爲5這時將發生指針越界的現象,再次印證了原函數的動作。

 

CString a( " hello world " );
char * b = a.GetBuffer( 0
);
strcpy(b,
" guanchanghui "
);
a.ReleaseBuffer();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章