char* GetBuffer( int nMinBufLength )
throw( CMemoryException );
nMinBufLength
The minimum size of the CString character buffer in bytes. You do not need to allow space for a null terminator.
Returns a pointer to the internal character buffer for the CString object. The returned pointer to char 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 GetBuffer is invalid after the call to ReleaseBuffer or any other CString operation.
The buffer memory will be freed automatically when the CString object is destroyed.
Note:
If you keep track of the string length yourself, you need not append the terminating null byte. You must, however, specify the final string length when you release the buffer with ReleaseBuffer, or you can pass -1 for the length and ReleaseBuffer will perform a strlen on the buffer to determine its length.
A char pointer to the object's (usually null-terminated) ASCII character buffer.
CString s;
char* p = s.GetBuffer(10); // Allocate space for 10 characters
s = "abcdefg"; // p is still valid because length of s is 7
characters
p[1] = 'B'; // Change 'b' to 'B'
#ifdef _DEBUG
afxDump << "char* p " << (void*) p << ":" << p << "\\n";
#endif
char* q = s.GetBuffer(12); // Get a new, larger buffer
// q is a different address than p, but the string is the same.
#ifdef _DEBUG
afxDump << "char* q " << (void*) q << ":" << q << "\\n";
#endif
s += "hij"; // String length is still smaller than 12
#ifdef _DEBUG
afxDump << "char* q " << (void*) q << ":" << q << "\\n";
#endif
s += "klmnop"; // Now it is larger than 12, so the characters
// Are moved, and q is no longer valid
#ifdef _DEBUG
afxDump << "char* q " << (void*) q << ":" << q << "\\n";
afxDump << "CString s " << s << "\\n"; // s contains
"aBcdefghijklmnop"
#endif
s.ReleaseBuffer();