Share via


CString::GetBufferSetLength

LPTSTRGetBufferSetLength(intnNewLength**);**
throw(CMemoryException);

Return Value

An LPTSTR pointer to the object’s (null-terminated) character buffer.

Parameters

nNewLength

The exact size of the CString character buffer in characters.

Remarks

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:

  • in the Win32 SDK Programmer’s Reference

  • in the Win32 SDK Programmer’s Reference

  • in the Win32 SDK Programmer’s Reference

Example

CString str;
LPTSTR pstr = str.GetBufferSetLength(3);
pstr[0] = 'I';
pstr[1] = 'c';
pstr[2] = 'e';

// No need for trailing zero or call to ReleaseBuffer()
// because GetBufferSetLength() set it for us!

str += _T(" hockey is best!");

CString OverviewClass MembersHierarchy Chart

See Also   CString::GetBuffer, CString::ReleaseBuffer