我在程序中用的是unicode。
下面一段代码void ClassA::GetPairFromStr(const CString& _str)
{
CString _strTemp(_str);
int ret=_strTemp.Find(_T("to"));
_strTemp=_strTemp.Left(ret);
}然后调试的时候我在函数里面看到的_str的值是"A to B";
执行完后_strTemp的值未变。我换成下面的代码就能执行正确;CString _strTemp("A to B");
int ret=_strTemp.Find(_T("to"));
_strTemp=_strTemp.Left(ret);问几个问题。
1.我用的unicode版本,为什么CString _strTemp("A to B");能执行成功?不用_T的吗?
2.为什么我上面用传参数的方式 使用_strTemp=_strTemp.Left(ret),却得不到正确的结果?

解决方案 »

  1.   

    CString _strTemp(_T("A to B"));
      

  2.   

    因为CString的构造函数有 LPSTR 与 LPWSTR 的参数,所以"abc"也可以.
      

  3.   


    那是因为你的源字符串_str在GetBuffer后没有调用ReleaseBuffer导致的
    因为没有调用ReleaseBuffer,导致你的_str.GetLength()返回0,所以Left总是返回相同字符串很多学习MFC的人在使用CString中都存在这样的不规范用法
    这在VC6中的CString是没有问题,但是在之后的版本中GetBuffer和ReleaseBuffer一定要配套使用
    CStringT Left( _In_ int nCount ) const
    {
    // nCount is in XCHARs
    if (nCount < 0)
    nCount = 0; int nLength = GetLength();
    if( nCount >= nLength )
    {
    return( *this );
    } return( CStringT( GetString(), nCount, GetManager() ) );
    }
      

  4.   

    新版本的CString中GetLength不再每次计算字符串长度,而是从缓存的变量获取长度
    这也许是基于优化性能的考虑
    int GetLength() const throw()
    {
    return( GetData()->nDataLength );
    }