CString的GetBuffer用法,GetBuffer本质,GetBuffer常见问题解决方法

本文详细探讨了MFC中CString类的GetBuffer方法,讲解了其功能、作用及常见问题。GetBuffer返回内部字符缓冲区的非const指针,允许直接修改字符串内容,但必须在修改后调用ReleaseBuffer。不正确使用可能导致CString对象状态错误。文章通过实例展示了GetBuffer错误用法及后果,并提出避免此类错误的建议。
摘要由CSDN通过智能技术生成
 

一.函数原型

CString::GetBuffer

LPTSTR GetBuffer( int nMinBufLength );

throw( CMemoryException );

Return Value

An LPTSTR pointer to the object’s (null-terminated) character buffer.

Parameters

nMinBufLength

The minimum size of the character buffer in characters. This value does not include space for a null terminator.

Remarks

Returns a pointer to the internal character buffer for the CString object. The returned LPTSTR is not const and thus allows direct modification of CString contents.

If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.

二.函数作用及使用范围

对一个CString变量,你可以使用的唯一合法转换符是LPCTSTR,直接转换成非常量指针(LPTSTR-[const] char*)是错误的。正确的得到一个指向缓冲区的非常量指针的方法是调用GetBuffer()方法。

GetBuffer()主要作用是将字符串的缓冲区长度锁定,releaseBuffer则是解除锁定,使得CString对象在以后的代码中继续可以实现长度自适应增长的功能。

CString ::GetBuffer有两个重载版本:

LPTSTR GetBuffer( );LPTSTR GetBuffer(int nMinBufferLength);

在第二个版本中,当设定的长度小于原字符串长度时,nMinBufLength = nOldLen,该参数会被忽

略,不分配内存,指向原CString;当设定的长度大于原字符串本身的长度时就要重新分配(reallocate)一块比较大的空间出来。而调用第一个版本时,应如通过传入0来调用第二个版本一样。

是否需要在GetBufer后面调用ReleaseBuffer(),是根据你的后面的程序是否需要继续使用该字符串变量,并且是否动态改变其长度而定的。如果你GetBuffer以后程序自函数就退出,局部变量都不存在了,调用不调用ReleaseBuffer没什么意义了。

最典型的应用就是读取文件:

CFile file;

// FILE_NAME 为实现定义好的文件名称

if(file.Open(FILE_NAME,CFile::modeRead))

{

       CString szContent;

       int nFileLength = file.GetLength();

       file.Read(szContent.GetBuffer(nFileLength),nFileLength);

       szContent.ReleaseBuffer();

       // 取得文件內容放在szContent中,我们之后可以对其操作

}

三.测试

以下就CString::GetBuffer,做简单测试:

测试1

// example for CString::GetBuffer

 

#include <stdio.h>

#include <afx.h>

 

void main(void)

{    

       CString s( "abcd" );

       printf("(1)before GetBuffer:\n");

       printf("CString s.length=%d\n",s.GetLength());

       printf("CString s=%s\n",s);

      

       LPTSTR p = s.GetBuffer( 2 );

      

       printf("(2)after GetBuffer and before ReleaseBuffer:\n");

       printf("LPTSTR p=%s\n",p);    

       printf("p.length=%d\n",strlen(p));

printf("CString s=%s\n",s);      

       printf("CString s.length=%d\n",s.GetLength());

      

 

       s.ReleaseBuffer( );

       printf("(3)after ReleaseBuffer:\n");

       printf("LPTSTR p=%s\n",p);    

       printf("p.length=%d\

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值