Lptstr Getbuffer ( Int Nminbuflength ) This function is a more practical function of cstring. See the following example:
Getbuffer (INT nminbuflength); the parameter problem has been quite confusing, and the website information is not very good. Please refer to the msdn explanation.
Parameters
Nminbuflength
The minimum size of the Character Buffer in characters. This value does not include space for a null Terminator.
Obtain the minimum buffer length. Of course, this is a parameter set by ourselves. Its prototype is defined as follows:
Lptstr cstring: getbuffer (INT nminbuflength)
{
Assert (nminbuflength> = 0 );
If (getdata ()-> nrefs> 1 | nminbuflength> getdata ()-> nalloclength)
{
# Ifdef _ debug
// Give a warning in case locked string becomes unlocked
If (getdata ()! = _ Afxdatanil & getdata ()-> nrefs <0)
Trace0 ("Warning: getbuffer on locked cstring creates unlocked cstring! /N ");
# Endif
// We have to grow the buffer
Cstringdata * polddata = getdata ();
Int noldlen = getdata ()-> ndatalength; // allocbuffer will Tromp it
If (nminbuflength <noldlen)
Nminbuflength = noldlen;
Allocbuffer (nminbuflength );
Memcpy (m_pchdata, polddata-> data (), (noldlen + 1) * sizeof (tchar ));
Getdata ()-> ndatalength = noldlen;
Cstring: release (polddata );
}
Assert (getdata ()-> nrefs <= 1 );
// Return a pointer to the character storage for this string
Assert (m_pchdata! = NULL );
Return m_pchdata;
}
The above code is clear. When the set length is smaller than the original string length, nminbuflength = noldlen, and then allocate the corresponding memory, when the length you set is greater than the length of the original string, you need to allocate a large space. In this case, you can perform the string docking operation. See the following code:
Cstring S;
S = "ABC ";
Char * P = S. getbuffer (6 );
Int L = S. getlength ();
Memcpy (p + L, "111", 3 );
Char * c = new char [6];
Memset (C, '1', 3 );
Char * D = "Sss ";
Strcat (c, d );
Cstring E;
E = (lpctstr) C;
Afxmessagebox (E );
Afxmessagebox (s );
S. releasebuffer (); // surplus memory released, P is now invalid.
This code mainly examines the action of the getbuffer () function, in char * P = S. getbuffer (6), you can see P [6] = ''through debug, which means that it automatically adds an Terminator, if you allocate space of 5, the pointer may be out of bounds, which confirms the action of the original function again.
Cstring A ("Hello World ");
Char * B = A. getbuffer (0 );
Strcpy (B, "guanchanghui ");
A. releasebuffer ();
Where