Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should CString's GetBufferSetLength() have a matching ReleaseBuffer() call?

Tags:

c++

string

atl

mfc

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:

  1. Those tests aren't complete.
  2. I'm interested in writing correct code according to CString's interface official specifications, not implementation-dependent code that may work on a given version of VS and then fail on the next one.
like image 994
Mr.C64 Avatar asked Sep 01 '16 15:09

Mr.C64


2 Answers

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.

like image 105
Mark Ransom Avatar answered Sep 20 '22 18:09

Mark Ransom


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.


Note: It is not required for an implementation to fail, when used without following it's documented protocol. As a consequence, you cannot test, whether all steps of that protocol are required.
like image 34
IInspectable Avatar answered Sep 22 '22 18:09

IInspectable