2016-11-16 55 views
2

我目前正在學習MFC庫,我想知道爲什麼我應該使用GetBuffer成員,它返回指向CString對象緩衝區的指針,以允許讀取和更改該對象中的字符的其他成員函數? 比如爲什麼我應該做的(代碼修改CString對象的第一個字符):爲什麼我應該使用CString的GetBuffer成員而不是SetAt?

CString aString(_T("String")); //new CString object 
LPTSTR p = aString.GetBuffer(); //create new pointer to aString buffer 
_tcsncpy(p, LPCTSTR(_T("a")), 1); //set first character to 'a' 
aString.ReleaseBuffer(); //free allocated memory 

相反的:

CString aStr(_T("String")); //new CString object 
aStr.SetAt(0, _T('a')); //set character at 0 position to 'a' 

我想有一個更合適的應用程序中使用的GetBuffer()成員,但我無法弄清楚它可能是什麼......這個函數需要ReleaseBuffer()來釋放內存,並且當沒有調用ReleaseBuffer()時我可能導致內存泄漏。使用它有什麼好處嗎?

回答

2

在上例中,最好使用SetAt方法。

在某些情況下,您需要GetBuffer直接訪問緩衝區,主要是在使用WinAPI函數時。例如,使用::GetWindowText與WinAPI的代碼,你需要如下分配緩衝區:

int len = ::GetWindowTextLength(m_hWnd) + 1; 
char *buf = new char[len]; 
::GetWindowText(m_hWnd, buf, len); 
... 
delete[] buf; 

同樣的事情可以在MFC完成與CWnd::GetWindowText(CString&)。但MFC必須使用相同的基本WinAPI函數,通過GetBuffer。 MFC的實現的CWnd::GetWindowText大致如下:

void CWnd::GetWindowText(CString &str) 
{ 
    int nLen = ::GetWindowTextLength(m_hWnd); 
    ::GetWindowText(m_hWnd, str.GetBufferSetLength(nLen), nLen+1); 
    str.ReleaseBuffer(); 
} 
1

不要使用GetBuffer除非你別無選擇。正是因爲(1)你已經知道的原因,必須遵循ReleaseBuffer,你可能會忘記這樣做,導致資源泄漏。 (2)您可能會無意中對底層數據進行更改,使其在某些方面不一致。通常,函數GetString,SetString,GetAt和SetAt將執行你所需要的並且沒有缺點。喜歡他們。

相關問題