MFC CSTRING Learning Notes-1

zhaozj2021-02-16  42

CString Class Research (1)

CSTRING Initialize

CString Use CStringData Structure as a buffer to store data and other information.

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);

}

To create a new cstring object,

IF _AFXDLL IS Defined, MFC Invoke Init () function to set m_pchdata = afxemptyString.m_pchdata,

// from strcore.cpp

#ifdef _AFXDLL

CString :: cstring ()

{

INIT ();

}

#ENDIF

// from AFX.INL

_AFX_INLINE VOID CSTRING :: Init ()

{m_pchdata = afxemptyString.m_pchdata;}

OR IF_AFXDLL IS Not Defeed, Mfc Will Set M_Pchdata = AFXEMPTYSTRING.M_PCHDATA in CONSTRUCTION FUNCTION.

// from AFX.INL

#ifndef _afxdll

_AFX_INLINE CSTRING :: CString ()

{m_pchdata = afxemptyString.m_pchdata;}

#ENDIF

To Get Afxemptystring Reference, AfxGetemptystring () is invoked.

Const Cstring & AfxApi AFXGETEMPTYSTYSTRING ()

{RETURN * (CString *) & _Afxpchnil;

SO, WHEN INITIALIZING, MFC MAKE The Data Buffer (a class member variable, m_pchdata) Point to an exist, system defined, EMPTY BUFFER (_AFXPCHNIL).

In an other words, if 2 CString objects are created without value set, their data buffer will point to one buffer in memory (_afxPchNil), their buffer's address are same. But the two object are not same, so address of object are different.

ORSET FUNCPY or MEMSET FUNCTION TO SET An Non-Null Value To Mfc CString Init Buffer (_AFXPchnil), All The Cstring Which Will Be Initialized by The Same Value Other Than Null ('/ 0').

For example:

CSTRING STR1, STR2;

Memcpy (LPCTSTR) STR1, "ABCD", 5);

CString str3;

str1and str2 are initialized as null, but if we change the value of str1 to "abcd", the str2's value will be changed to "abcd" at the same time. and then, if we create a new object without init value, the default Value of str3 is "abcd" Also. That Means, The System Defined "Null" buffer's value is call to "abcd".

2. EMPTY CSTRING

The Empty () function will delete the current buffer and allocate new buffer. When the new buffer is allocated successfully, MFC will invoke init () function to initialize the value to system defined "null" buffer's value (_afxPchNil).

Void cstring :: release ()

{

IF (getData ()! = _afxDatanil)

{

ASSERT (GetData () -> NREFS! = 0);

IF (InterlockedDecrement (& getData () -> nrefs) <= 0)

Freedata (GetData ());

INIT ();

}

}

Of Course, IF We Have Changed The Value of System Defined "Null" buffer (_AFXPCHNIL), The EMPTY () Function Will Get The New Value.

CSTRING STR1, STR2;

Memcpy (LPCTSTR) STR1, "ABCD", 5);

CString str3;

Str3.empty ();

When str3.empty () executed, The str3's value is "abcd", not "null".

转载请注明原文地址:https://www.9cbs.com/read-27794.html

New Post(0)