怎么快速实现两CString对象的快速复制?
例如
CString p("abcd");
CString q;//q=p;//这里指向同一内存块,所以我要COPY出来for(int i=0;i<p.GetLength();i++)
{
if(p.GetAt(i)!='\0')
q=q+p.GetAt(i);
}//太麻烦了,如果串较长而且复制操作较多的话,很影响性能
//所以我想请问各位高手,是不是有什么好的办法?
例如
CString p("abcd");
CString q;//q=p;//这里指向同一内存块,所以我要COPY出来for(int i=0;i<p.GetLength();i++)
{
if(p.GetAt(i)!='\0')
q=q+p.GetAt(i);
}//太麻烦了,如果串较长而且复制操作较多的话,很影响性能
//所以我想请问各位高手,是不是有什么好的办法?
不推荐用CString,很不好用,经常会出些莫名其妙的问题,特别是涉及指针的时候
不如用char*好点
CString Q;
{
CString p("abcd");
Q=p;
}
......现在的Q是什么?有可能是abcd,也有可能不是,原因我想大家都明白
所以我才要重新将p指向的内存块复制一份到Q
CString str2=CString(str1);
用构造复制函数可以了吧!
我试过了,很爽
在这里不要跟我谈什么效率的问题
{
CString p("abcd");
Q=p;
}
这有什么问题吗?
一点问题都没有,=号用的就是内存复制的方式
给大家贴一段MFC的CStringr的重载操作符代码
{
if (m_pchData != stringSrc.m_pchData)
{
if ((GetData()->nRefs < 0 && GetData() != _afxDataNil) ||
stringSrc.GetData()->nRefs < 0)
{
// actual copy necessary since one of the strings is locked
AssignCopy(stringSrc.GetData()->nDataLength, stringSrc.m_pchData);
}
else
{
// can just copy references around
Release();
ASSERT(stringSrc.GetData() != _afxDataNil);
m_pchData = stringSrc.m_pchData;
InterlockedIncrement(&GetData()->nRefs);
}
}
return *this;
}
m_pchData是一个共用的(堆分配)的变量,我没有出问题,我觉得CString是VC最好用,和用得最多的一个类!
可以这样:q.Format("%s", p);