簡體   English   中英

為什么我應該使用CString的GetBuffer成員而不是SetAt?

[英]Why should I use GetBuffer member of CString instead of SetAt?

我目前正在研究MFC庫,我想知道為什么我應該使用GetBuffer成員,該成員比其他允許讀取和更改該對象字符的成員函數返回指向CString對象緩沖區的指針? 例如,為什么要這樣做(代碼更改了CString對象的第一個字符):

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()為時,可能會導致內存泄漏不叫。 使用它有什么好處嗎?

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

在某些情況下,主要是與WinAPI函數一起使用時,您需要GetBuffer直接訪問緩沖區。 例如,要在WinAPI代碼中使用::GetWindowText ,則需要按以下方式分配緩沖區:

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

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

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

除非別無選擇,否則不要使用GetBuffer 正是由於(1)的原因,您必須忘記使用ReleaseBuffer否則可能會忘記這樣做,從而導致資源泄漏。 並且(2)您可能會無意中對基礎數據進行更改,從而使其在某種程度上不一致。 函數GetString,SetString,GetAt和SetAt通常會滿足您的需要,並且沒有缺點。 喜歡他們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM