读书人

CString:GetBuffer的有关问题

发布时间: 2012-02-04 15:43:09 作者: rapoo

CString::GetBuffer的问题
PXSTR GetBuffer(
int nMinBufferLength
);
PXSTR GetBuffer();

MSDN上说
If nMinBufferLength is larger than the length of the current buffer, GetBuffer destroys the current buffer, replaces it with a buffer of the requested size, and resets the object reference count to zero.

如果nMinBufferLength的值大于当前缓冲区的大小,就会重新分配一个大小为nMinBufferLength的缓冲区然后释放原来的缓冲区,再看下面的代码:

C/C++ code
#include "iostream"#define _AFXDLL#include "afx.h"#pragma comment(linker,"/ENTRY:TEST")using namespace std;using namespace ATL;int TEST() {        CString str = "test";    char* ss = str.GetBuffer();    //得到现在的缓冲区    int x = str.GetAllocLength();    //得到现在的缓冲区大小,4        char* sss = str.GetBuffer(1000);    //得到一个缓冲区,大小要求为1000,这里应该把以前的缓冲区释放掉然后申请 一个新的。    int xx = str.GetAllocLength();    //得到现在的缓冲区大小,1000        cout << static_cast<void*>(ss) << endl;    //0039A810,原来的缓冲区地址    cout << static_cast<void*>(sss) << endl;    //0039A810,现在的缓冲区地址    //////问题    ///为什么重新分配了缓冲区,地址依然是原来的那个地址?sss为什么还是指向了原来的那个缓冲区的地址?        cin.get();    return 0;}

问题在注释里面,谢谢回答。

[解决办法]
这个跟环境有关吧,以前的缓冲区释放掉后没有其它的程序申请,新的内存位置可能与原来相同,只是大小不同而已
不过我的测试(VS2008 64bit+WIN7 64bit)结果与你的就不同了,结果为:
00000000004DB2A8
00000000004DA898

读书人网 >C++

热点推荐