From CString to char*, ReleaseBuffer()
must be used after GetBuffer()
. But why? What will happen if I don't use ReleaseBuffer()
after GetBuffer()
?
Can somebody show me an example? Thanks.
From CString to char*, ReleaseBuffer()
must be used after GetBuffer()
. But why? What will happen if I don't use ReleaseBuffer()
after GetBuffer()
?
Can somebody show me an example? Thanks.
I'm not sure that this will cause a memory leak, but you must call ReleaseBuffer
to ensure that the private members of CString
are updated. For example, ReleaseBuffer
will update the length field of the CString
by looking for the terminating null
character.
const
pointer instead, which doesn't require GetBuffer
- just a cast to PCTSTR
. –
Bosson What will happen if I don't use
ReleaseBuffer()
afterGetBuffer()
?
I haven't used MFC (and hopefully won't ever have to touch it with a ten-foot pole) but, as a rule of thumb, whenever you have an API that has both GetXXX()
and ReleaseXXX()
(especially when the result of GetXXX()
conveniently is of the type that ReleaseXXX()
takes) -- then when you forget to call ReleaseXXX()
for every one of your GetXXX()
calls, you will leak an XXX
.
GetXXX()
and ReleaseXXX()
don't come in pairs just plain sucks... Anyway, from msdn.microsoft.com/en-us/library/awkwbzyc.aspx: "After you modify the contents of a CString object directly, you must call ReleaseBuffer before you call any other CString member functions." –
Winery Here's an example of how I used CString::GetBuffer()
and CString::ReleaseBuffer()
:
LPTSTR pUnitBuffer = pAPBElement->m_strUnits.GetBuffer(APB_UNIT_SIZE);
if (pUnitBuffer != "")
{
if (strncmp(pAPBElement->m_strUnits, (char*)pszBuffer[nLoop - nFirst], APB_UNIT_SIZE) != 0)
{
LPTSTR pUnitOriginal = pAPBElement->m_strOriginal.GetBuffer(APB_UNIT_SIZE);
strncpy(pUnitBuffer,
(char*)&pszBuffer[nLoop - nFirst],
APB_UNIT_SIZE);
strncpy(pUnitOriginal,
(char*)&pszBuffer[nLoop - nFirst],
APB_UNIT_SIZE);
pAPBElement->m_strOriginal.ReleaseBuffer();
}
}
pAPBElement->m_strUnits.ReleaseBuffer();
If you do not modify the contents of the CString using the pointer obtained using GetBuffer(), you do NOT need to call ReleaseBuffer() afterwards
© 2022 - 2024 — McMap. All rights reserved.