CString 有一个转换函数
operator PXSTR ()
{
return data;//假设是data
}
1.
PXSTR GetBuffer()
{
CStringData* pData = GetData();
if( pData->IsShared() )
{
Fork( pData->nDataLength );
}
return( m_pszData );
}
关于if语句,这就是CString实现 copy_on_write机制的方法,Fork里面就是重新申请一块内存然后复制过来
在赋值语句里面对data只是AddRef()了一下。
2. GetBuffer(int minlength)方法
如果minlength 小于自身data的长度,则直接返回,否则要重新申请内存,要注意的是:重新申请内存会将原来的内容释放掉
ReleaseBuffer():
更新字符长度,并在最后加一个'\0'
3.LockBuffer():
将数据的引用计算-1,即表示:如果将其赋给其他CString,将是深拷贝,如果被赋予新值,将也是深拷贝,但原先内容被释放了,这是不可取的
By calling LockBuffer, you create a copy of the string, and then set the reference count to –1. When the reference count is set to –1, the string in the buffer is considered to be in a locked state. While in a locked state, the string is protected in two ways:
- No other string can get a reference to the data in the locked string, even if that string is assigned to the locked string.
- The locked string will never reference another string, even if that other string is copied to the locked string.
By locking the string in the buffer, you ensure that the exclusive hold of the string on the buffer remains intact.
After you have finished with LockBuffer, call UnlockBuffer to reset the reference count to 1.
If you call GetBuffer on a locked buffer, and you set theGetBuffer parameter nMinBufLength to greater than the length of the current buffer, you lose the buffer lock. Such a call toGetBuffer destroys the current buffer, replaces it with a buffer of the requested size, and resets the reference count to zero.