现在的位置: 首页 > 综合 > 正文

CString GetBuffer() and ReleaseBuffer()

2012年11月13日 ⁄ 综合 ⁄ 共 1667字 ⁄ 字号 评论关闭

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();

其中

抱歉!评论已关闭.