CString::GetBuffer
LPTSTR GetBuffer( int nMinBufLength );
throw( CMemoryException );
Return Value
An LPTSTR pointer to the object’s (null-terminated) character buffer.
Parameters
nMinBufLength
The minimum size of the character buffer in characters. This value does not include space for a null terminator.
Remarks
Returns a pointer to the internal character buffer for the CString object. The returned LPTSTR 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 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 reallocated if you do not change the length of the CString.
The buffer memory will be freed automatically when the CString object is destroyed. GetBuffer后,在对象销毁时会自动清理释放内存,不需要专门用ReleaseBuffer()来专门释放,但是在对象销毁前,如果你需要用该长度变量且需要更新该长度变量的情况下,你就需要调用ReleaseBuffer()来专门释放内存。
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, you should pass –1 for the length to ReleaseBuffer and ReleaseBuffer will perform a strlen on the buffer to determine its length.
对一个CString变量,你可以使用的唯一合法转换符是LPCTSTR,直接转换成非常量指针(LPTSTR-[const] char*)是错误的。正确的得到一个指向缓冲区的非常量指针的方法是调用GetBuffer()方法。
GetBuffer()主要作用是将字符串的缓冲区长度锁定,releaseBuffer则是解除锁定,使得CString对象在以后的代码中继续可以实现长度自适应增长的功能。
Example
// CstringTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "CstringTest.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // The one and only application object CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; // initialize MFC and print and error on failure if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs cerr << _T("Fatal Error: MFC initialization failed") << endl; nRetCode = 1; } else { // TODO: code your application's behavior here. CString csStr; csStr = "abcdefghijklnm"; cout << (LPCTSTR)csStr << endl; //CString输出方式一 cout << csStr.GetBuffer(0) << endl; //CString输出方式二 cout << csStr.GetLength() << endl; //LPTSTR pStr = csStr.GetBuffer(0); //申请内存不够,strcpy奔溃 //LPTSTR pStr = csStr.GetBuffer(19); //申请内存不够,strcpy奔溃 LPTSTR pStr = csStr.GetBuffer(20); strcpy(pStr,"12345678901234567890"); csStr.ReleaseBuffer(); pStr = NULL; cout << (LPCTSTR)csStr << endl; } return nRetCode; }