CString GetLength() returns 0

Debugging the program today, there is clearly a value in the CS ring object. The return value of CString.GetLength is 0. The code is as follows

CString m_sername;

CString s="hello "

 m_sername=s;

At this point s.GetLength()=0;

After searching on the Internet, I found the reason in str1.ReleaseBuffer(); In fact, CString::ReleaseBuffer is just an image, and it is a name corresponding to GetBuffer.

Let's take a look at the code of ReleaseBuffer in MFC:

     void ReleaseBuffer( int nNewLength = -1 )

     {

          if( nNewLength == -1 )

          {

               nNewLength = StringLength( m_pszData );

          }

          SetLength( nNewLength );

     }

Obviously ReleaseBuffer only has one function, that is to update the length of the string. In CString, the length of the string obtained by GetLength is not calculated dynamically, but is calculated after the assignment operation and stored in an int variable. When CString is directly modified through GetBuffer, the int variable cannot be automatically updated, so there is ReleaseBuffer.

Therefore, the above code plus s.ReleaseBuffer(); and then s.GetLength() is OK.

This article refers to the source http://iqnix.blog.163.com/blog/static/217219820098441153853/ , thank you! !

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325358973&siteId=291194637