CString GetBuffer() and ReleaseBuffer()

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 GetBuffer() and ReleaseBuffer()  CString s;
CString GetBuffer() and ReleaseBuffer() s 
=   " abc " ;
CString GetBuffer() and ReleaseBuffer() 
char *  p  =  s.GetBuffer( 6 );
CString GetBuffer() and ReleaseBuffer()  
int  l = s.GetLength();
CString GetBuffer() and ReleaseBuffer() memcpy(p
+ l, " 111 " , 3 );
CString GetBuffer() and ReleaseBuffer() 
char *  c = new   char [ 6 ];
CString GetBuffer() and ReleaseBuffer() memset(c,
' 1 ' , 3 );
CString GetBuffer() and ReleaseBuffer() 
char *  d = " sss " ;
CString GetBuffer() and ReleaseBuffer() strcat(c,d);
CString GetBuffer() and ReleaseBuffer() CString e;
CString GetBuffer() and ReleaseBuffer() e
= (LPCTSTR)c;
CString GetBuffer() and ReleaseBuffer() AfxMessageBox(e);
CString GetBuffer() and ReleaseBuffer() AfxMessageBox(s);
CString GetBuffer() and ReleaseBuffer()
CString GetBuffer() and ReleaseBuffer() s.ReleaseBuffer();  
//  Surplus memory released, p is now invalid.
CString GetBuffer() and ReleaseBuffer()

CString GetBuffer() and ReleaseBuffer()
CString GetBuffer() and ReleaseBuffer()

这段代码主要是考察GetBuffer()函数的动作,在char* p=s.GetBuffer(6),通过debug 可以看到p[6]='',这说明他自动加上了一个结束符,如果你分配空间为5这时将发生指针越界的现象,再次印证了原函数的动作。

CString GetBuffer() and ReleaseBuffer() CString a( " hello world " );
CString GetBuffer() and ReleaseBuffer()
char *  b = a.GetBuffer( 0 );
CString GetBuffer() and ReleaseBuffer()strcpy(b,
" guanchanghui " );
CString GetBuffer() and ReleaseBuffer()a.ReleaseBuffer();

其中

你可能感兴趣的:(String)