永发信息网

cstring getbuffer后必须要releasebuffer吗

答案:2  悬赏:60  手机版
解决时间 2021-02-01 17:25
  • 提问者网友:捧腹剧
  • 2021-02-01 10:37
cstring getbuffer后必须要releasebuffer吗
最佳答案
  • 五星知识达人网友:西风乍起
  • 2021-02-01 11:59
The GetBuffer and ReleaseBuffer memberfunctions allow you to gain access to the internal character buffer of aCString object and modify it directly.

Call GetBuffer for a CString object andspecify the length of the buffer you require. Use the pointer returned byGetBuffer to write characters directly into the CString object.

If you use the pointer returned byGetBuffer to change the string contents, you must call ReleaseBuffer beforeusing any other CSimpleStringT member methods.

Call ReleaseBuffer for the CString objectto update all the internal CString state information, such as the length of thestring. After modifying a CString object's contents directly, you must call ReleaseBufferbefore calling any other CString member functions.

从MSDN的描述中可以知道,GetBuffer让我们获得CString对象字符内存的操作权,这样就可以操作CString对象了。但修改CString对象后,对象的状态信息并没有更新,于是便有了ReleaseBuffer。如果你之后需要继续使用该CString对象,就需要调用ReleaseBuffer。
全部回答
  • 1楼网友:掌灯师
  • 2021-02-01 12:33
从msdn的官方解释来说,getbuffer是将字符串的缓冲区长度锁定,releasebuffer是解除锁定,那么在进行cstring操作前,应该releasebuffer。 其实从底层代码上看,是这样的,messagebox(k1)不报错,是因为地址空间确实已经赋值,内存中有东西。但实际上,在release之前,不仅getat报错,getlength获取到的长度是0,那么为什么呢,我们看releasebuffer的底层代码: void cstring::releasebuffer(int nnewlength) { copybeforewrite(); // just in case getbuffer was not called if (nnewlength == -1) nnewlength = lstrlen(m_pchdata); // zero terminated assert(nnewlength <= getdata()->nalloclength); getdata()->ndatalength = nnewlength; m_pchdata[nnewlength] = '\0'; } void cstring::copybeforewrite() { if (getdata()->nrefs > 1) { cstringdata* pdata = getdata(); release(); allocbuffer(pdata->ndatalength); memcpy(m_pchdata, pdata->data(), (pdata->ndatalength+1)*sizeof(tchar)); } assert(getdata()->nrefs <= 1); } 从这里可以看出,其实cstring的各种变量,在releasebuffer之前,是没有被更新的,而getat函数需要获取cstring长度,并且通过getdata来获取数据(而不是直接从内存),这样肯定会出现断言错误。 如果希望getbuffer并进行内存操作之后,cstring各种功能,只能先调用releasebuffer更新cstring数据才可以。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯