c++中std::string使用的一点新体会

    由于近期项目进入联调阶段,很多问题在这个过程中发现,其中有一个很有趣,记录一下,希望大家不要犯类似的错误。不说其他的,直接上代码。

代码如下:

MsLink * __stdcall CLS_XXXXX::GetClientByIP(const std::string &_strIP)
{
  std::map::iterator it = m_mapLink.find(_strIP);
if(it != m_mapLink.end())
{
return it->second;
}

return NULL;
}

    很简答的代码,这个m_mapLink里面在实际的调试里面有两个值:{“10.30.40.110“,”10.30.40.124“},传递进来的参数_strIP我也确定是”10.30.40.124“

但是很怪异的是在m_mapLink里面竟然找不到。通过VS2008调试器查看变量值看不出任何不一致,同时写demo发现正常情况下也是能找到。但此处就是

不能根据map的first找到second,why?后来花了很大的力气才找到原因,原因就是存m_mapLink的first的时候使用和std::string(cIP, 16),这种方式,而

我们传进来的_strIP = ”10.30.40.124“是这样赋值的。现在我就把c++中关于这两种的区别总结一下,先看一个为此写的小demo:

       std::string strTest1 = "10.30.40.124";
int iTest1Len = strTest1.length();   //iTest1Len =12


char cIP[16] = {0}; 
strcpy_s(cIP, 16, strTest1.c_str());
std::string strTest2(cIP, 16);
int iTest2Len = strTest2.length();    //iTest2Len = 16

if (strTest1 == strTest2)
{
MessageBox("strTest1 == strTest2", "提示", MB_OK|MB_TOPMOST);
}

很显然,这个地方strTest1肯定和strTest是不相等的(长度不一致),但是这是我们知道做了什么处理,但是如果通过传值给你一个strTest2的字符串,相信我,你也会感到

很诧异,为什么看似一样的东西却不一样。跟进std::string的源码看一下就清楚(个人分析,如有错误请指出):

templateclass _Traits,
class _Alloc> inline
bool __CLRCALL_OR_CDECL operator==(
const basic_string<_Elem, _Traits, _Alloc>& _Left,
const basic_string<_Elem, _Traits, _Alloc>& _Right)
{ // test for string equality
return (_Left.compare(_Right) == 0);
}


int __CLR_OR_THIS_CALL compare(const _Myt& _Right) const
{ // compare [0, _Mysize) with _Right
return (compare(0, _Mysize, _Right._Myptr(), _Right.size()));
}


int __CLR_OR_THIS_CALL compare(size_type _Off,
size_type _N0, const _Elem *_Ptr, size_type _Count) const
{ // compare [_Off, _Off + _N0) with [_Ptr, _Ptr + _Count)

 #if _HAS_ITERATOR_DEBUGGING
if (_Count != 0)
_DEBUG_POINTER(_Ptr);
 #endif /* _HAS_ITERATOR_DEBUGGING */

if (_Mysize < _Off)
_String_base::_Xran();// _Off off end
if (_Mysize - _Off < _N0)
_N0 = _Mysize - _Off;// trim _N0 to size

size_type _Ans = _Traits::compare(_Myptr() + _Off, _Ptr,
_N0 < _Count ? _N0 : _Count);
return (_Ans != 0 ? (int)_Ans : _N0 < _Count ? -1
: _N0 == _Count ? 0 : +1);


其中_Traits::compare(_Myptr() + _Off, _Ptr,
_N0 < _Count ? _N0 : _Count);内部调用的是memcmp,这里就不再详细赘述,size_type _Ans = _Traits::compare(_Myptr() + _Off, _Ptr,
_N0 < _Count ? _N0 : _Count); 这句话中_Ans 返回的是0,但是通过_Ans != 0 ? (int)_Ans : _N0 < _Count ? -1
: _N0 == _Count ? 0 : +1比较后发现这两个字符串大小不一致,所以不相等。现在可以算终于弄明白为啥了,哈哈,就此打住。
}

你可能感兴趣的:(string,c++,iterator,debugging,basic,class)