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

    其中
  • 相关阅读:
    [School Regional Team Contest, Saratov, 2011]
    [Codeforces Round #125 (Div. 2)] B. Special Olympics(圆的关系问题)
    2020ICPC·小米 网络选拔赛第一场 G-Tree Projection (构造)
    [Codeforces Round #679 (Div. 2)] D. Shurikens (思维,树状数组)
    [Codeforces Round #677 (Div. 3)] G. Reducing Delivery Cost (dijkstra,枚举)
    [Codeforces Round #677 (Div. 3)] F. Zero Remainder Sum (DP)
    cogs 2652. 秘术「天文密葬法」(0/1分数规划 长链剖分 二分答案 dp
    cogs 1377. [NOI2011] NOI嘉年华 (dp
    cogs 1199选课(树形dp 背包或多叉转二叉
    Minimum spanning tree for each edge(倍增LCA)
  • 原文地址:https://www.cnblogs.com/rainbowzc/p/2422302.html
Copyright © 2020-2023  润新知