According to the MSDN documentation for CString's GetBufferSetLength()
, a call to that method should be followed by a matching call to ReleaseBuffer()
.
However, in the sample code in the same page, a comment states that calling ReleaseBuffer()
is unnecessary:
CSimpleString str(pMgr); LPTSTR pstr = str.GetBufferSetLength(3); pstr[0] = _T('C'); pstr[1] = _T('u'); pstr[2] = _T('p'); // No need for trailing zero or call to ReleaseBuffer() // because GetBufferSetLength() set it for us. str += _T(" soccer is best!"); ASSERT(_tcscmp(str, _T("Cup soccer is best!")) == 0);
So, should correct code call ReleaseBuffer()
after GetBufferSetLength()
, or is that call unnecessary?
EDIT
According to a few tests I did, sounds like calling ReleaseBuffer()
is unnecessary after GetBufferSetLength()
, but:
The purpose of ReleaseBuffer
is to sync the state of the C-style string that the buffer contains with the state of the CString
internal variables. Presumably this is just getting the final string length and storing it internally, and perhaps reallocating the buffer if there's a large discrepancy.
In the case of the example, the string length was stated to be exactly 3 characters. Since the size of the string didn't change via manipulation of the buffer, there's no need to update the length after that manipulation.
The documentation for CSimpleStringT::GetBufferSetLength is unambiguously clear:
If you use the pointer returned by CSimpleStringT::GetBufferSetLength to change the string contents, call ReleaseBuffer to update the internal state of CSimpleStringT before you use any other CSimpleStringT methods.
Sample code is not contractual. In the event, where sample code contradicts the formal specification, go with the formal specification. The formal specification is contractual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With