ReleaseBuffer只有一个作用,就是更新字符串的长度

本文详细解析了CString类在复制和更新字符串长度方面的应用,包括如何使用GetBuffer和ReleaseBuffer方法进行安全有效的字符串操作,并通过实例展示了不同操作的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

void CStringBufferDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here


CString WeatherZone = "";
int strLen = this->m_WeatherZone.GetLength();
memcpy(WeatherZone.GetBuffer(strLen),this->m_WeatherZone.GetBuffer(strLen),strLen);
WeatherZone.ReleaseBuffer();

CString  WeatherInfo = "";
strLen = this->m_szWeatherInfo.GetLength();
memcpy(WeatherInfo.GetBuffer(strLen),this->m_szWeatherInfo.GetBuffer(strLen),strLen);
WeatherInfo.ReleaseBuffer();

CString  Weatherglass= "";
strLen = this->m_szWeatherglass.GetLength();
memcpy(Weatherglass.GetBuffer(strLen),this->m_szWeatherglass.GetBuffer(strLen),strLen);
Weatherglass.ReleaseBuffer();

 CString weather = WeatherZone +" " +WeatherInfo +" "+Weatherglass;	

 SetDlgItemText(IDC_STATIC1,weather);
 // 为啥得带的这个weather 是"  "呢?而不是 "北京多云转晴 23~35度"呢?
 /*
 很明显ReleaseBuffer只有一个作用,就是更新字符串的长度。
 CString内,GetLength获取字符串长度并不是动态计算的,
 而是在赋值操作后计算并保存在一个int变量内的,
 当通过GetBuffer直接修改CString时,那个int变量并不可能自动更新,
 于是便有了ReleaseBuffer。	 
    其实,计算长度还能用strlen(),这个就算不ReleaseBuffer也不会出错,
	但如果不ReleaseBuffer,在+=这种赋值时字符串很可能会跟想要得到的不同。 
 */
}

void CStringBufferDlg::OnButton2() 
{
	// TODO: Add your control notification handler code here
	CString s="hello";	
    LPTSTR ps=s.GetBuffer(10);
	MessageBox(ps);
    strcpy(ps,"hi");
	MessageBox(ps);	
	MessageBox(s);	
	int len=s.GetLength();
	char buff[256];
	MessageBox(itoa(len,buff,10));
    s.ReleaseBuffer();	
	len=s.GetLength();
	MessageBox(itoa(len,buff,10));
}

void CStringBufferDlg::OnButton3() 
{
	// TODO: Add your control notification handler code here
	CString WeatherZone = "";
	int strLen = this->m_WeatherZone.GetLength();
	memcpy(WeatherZone.GetBuffer(strLen),this->m_WeatherZone.GetBuffer(strLen),strLen);
	//WeatherZone.ReleaseBuffer();
	
	CString  WeatherInfo = "";
	strLen = this->m_szWeatherInfo.GetLength();
	memcpy(WeatherInfo.GetBuffer(strLen),this->m_szWeatherInfo.GetBuffer(strLen),strLen);
	//WeatherInfo.ReleaseBuffer();
	
	CString  Weatherglass= "";
	strLen = this->m_szWeatherglass.GetLength();
	memcpy(Weatherglass.GetBuffer(strLen),this->m_szWeatherglass.GetBuffer(strLen),strLen);
	//Weatherglass.ReleaseBuffer();
	
	char buff[256];
	wsprintf(buff,"%s %s %s",WeatherZone.GetBuffer(0),WeatherInfo.GetBuffer(0),Weatherglass.GetBuffer(0));
	//CString weather = WeatherZone +" " +WeatherInfo +" "+Weatherglass;	
	
 SetDlgItemText(IDC_STATIC1,buff);	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值