struct CStringData
{
long nRefs; // reference count
int nDataLength; // length of data (including terminator)
int nAllocLength; // length of allocation
// TCHAR data[nAllocLength] TCHAR* data() // TCHAR* to managed data
{ return (TCHAR*)(this+1); }
};
我不太明白
TCHAR* data() // TCHAR* to managed data
{ return (TCHAR*)(this+1); }
中的 return (TCHAR*)(this+1); 这句的意思,望高人指点
{
long nRefs; // reference count
int nDataLength; // length of data (including terminator)
int nAllocLength; // length of allocation
// TCHAR data[nAllocLength] TCHAR* data() // TCHAR* to managed data
{ return (TCHAR*)(this+1); }
};
我不太明白
TCHAR* data() // TCHAR* to managed data
{ return (TCHAR*)(this+1); }
中的 return (TCHAR*)(this+1); 这句的意思,望高人指点
char* data() // TCHAR* to managed data
{
cout<<"this ="<<this<<endl;
cout<<"this+1 ="<<this+1<<endl;
return (char*)(this+1);
}输出this = 0012FF3C
this+1 = 0012FF48
而且siezof(struct CStringData )=12
this+1 - this = 12
CString的头就是一个CStringData,接下来就是真正的字符串的值
TCHAR* data() // TCHAR* to managed data
{ return (TCHAR*)(this+1); } 这个就是返回字符串的开始地址。首先是this+1,这样就是往前一个CStringData的长度,
得到这个指针后转换成TCHAR*,这个就是字符串的开始地址。
#define ROUND(x,y) (((x)+(y-1))&~(y-1))
#define ROUND4(x) ROUND(x, 4)
AFX_STATIC CFixedAlloc _afxAlloc64(ROUND4(65*sizeof(TCHAR)+sizeof(CStringData)));
AFX_STATIC CFixedAlloc _afxAlloc128(ROUND4(129*sizeof(TCHAR)+sizeof(CStringData)));
AFX_STATIC CFixedAlloc _afxAlloc256(ROUND4(257*sizeof(TCHAR)+sizeof(CStringData)));
AFX_STATIC CFixedAlloc _afxAlloc512(ROUND4(513*sizeof(TCHAR)+sizeof(CStringData)));#endif //!_DEBUGvoid CString::AllocBuffer(int nLen)
// always allocate one extra character for '\0' termination
// assumes [optimistically] that data length will equal allocation length
{
ASSERT(nLen >= 0);
ASSERT(nLen <= INT_MAX-1); // max size (enough room for 1 extra) if (nLen == 0)
Init();
else
{
CStringData* pData;
#ifndef _DEBUG
if (nLen <= 64)
{
pData = (CStringData*)_afxAlloc64.Alloc();
pData->nAllocLength = 64;
}
else if (nLen <= 128)
{
pData = (CStringData*)_afxAlloc128.Alloc();
pData->nAllocLength = 128;
}
else if (nLen <= 256)
{
pData = (CStringData*)_afxAlloc256.Alloc();
pData->nAllocLength = 256;
}
else if (nLen <= 512)
{
pData = (CStringData*)_afxAlloc512.Alloc();
pData->nAllocLength = 512;
}
else
#endif
{
pData = (CStringData*)
new BYTE[sizeof(CStringData) + (nLen+1)*sizeof(TCHAR)];
pData->nAllocLength = nLen;
}
pData->nRefs = 1;
pData->data()[nLen] = '\0';
pData->nDataLength = nLen;
m_pchData = pData->data();
}
}