LPTSTR GetBufferSetLength( int nNewLength );
throw( CMemoryException );
An LPTSTR pointer to the object’s (null-terminated) character buffer.
The exact size of the CString character buffer in characters.
Returns a pointer to the internal character buffer for the CString object, truncating or growing its length if necessary to exactly match the length specified in nNewLength. The returned LPTSTR pointer is not const and thus allows direct modification of CString contents.
If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CString member functions.
The address returned by GetBufferSetLength may not be valid after the call to ReleaseBuffer since additional CString operations may cause the CString buffer to be reallocated. The buffer will not be reassigned if you do not change the length of the CString.
The buffer memory will be freed automatically when the CString object is destroyed.
Note that if you keep track of the string length yourself, you should not append the terminating null character. You must, however, specify the final string length when you release the buffer with ReleaseBuffer. If you do append a terminating null character when you call ReleaseBuffer, you should pass –1 (the default) for the length. ReleaseBuffer will perform a strlen on the buffer to determine its length.
For more information about reference counting, see the following articles:
- http://msdn.microsoft.com/en-us/library/ms687260(v=vs.60) in the Win32 SDK Programmer’s Reference
- http://msdn.microsoft.com/en-us/library/ms693431(v=vs.60) in the Win32 SDK Programmer’s Reference
- http://msdn.microsoft.com/en-us/library/ms692481(v=vs.60) in the Win32 SDK Programmer’s Reference
CString str; LPTSTR pstr = str.GetBufferSetLength(3); pstr = 'I'; pstr = 'c'; pstr = 'e'; // No need for trailing zero or call to ReleaseBuffer() // because GetBufferSetLength() set it for us! str += _T(" hockey is best!");