我只看 MSVC 2008 的实现。他们确实优化(我省略了一些东西):
_Myt& __CLR_OR_THIS_CALL replace(size_type _Off,
size_type _N0, const _Myt& _Right, size_type _Roff, size_type _Count)
{
...
if (_Count <= _N0)
{ // hole doesn't get larger, just copy in substring
_Traits_helper::move_s<_Traits>(_Myptr() + _Off, _Myres - _Off,
_Myptr() + _Roff, _Count); // fill hole
_Traits_helper::move_s<_Traits>(_Myptr() + _Off + _Count, _Myres - _Off - _Count,
_Myptr() + _Off + _N0, _Nm); // move tail down
}
else if (_Roff <= _Off)
{ // hole gets larger, substring begins before hole
_Traits_helper::move_s<_Traits>(_Myptr() + _Off + _Count, _Myres - _Off - _Count,
_Myptr() + _Off + _N0, _Nm); // move tail down
_Traits_helper::move_s<_Traits>(_Myptr() + _Off, _Myres - _Off,
_Myptr() + _Roff, _Count); // fill hole
}
else if (_Off + _N0 <= _Roff)
{ // hole gets larger, substring begins after hole
_Traits_helper::move_s<_Traits>(_Myptr() + _Off + _Count, _Myres - _Off - _Count,
_Myptr() + _Off + _N0, _Nm); // move tail down
_Traits_helper::move_s<_Traits>(_Myptr() + _Off, _Myres - _Off,
_Myptr() + (_Roff + _Count - _N0), _Count); // fill hole
}
else
{ // hole gets larger, substring begins in hole
_Traits_helper::move_s<_Traits>(_Myptr() + _Off, _Myres - _Off,
_Myptr() + _Roff, _N0); // fill old hole
_Traits_helper::move_s<_Traits>(_Myptr() + _Off + _Count, _Myres - _Off - _Count,
_Myptr() + _Off + _N0, _Nm); // move tail down
_Traits_helper::move_s<_Traits>(_Myptr() + _Off + _N0, _Myres - _Off - _N0, _Myptr() + _Roff + _Count,
_Count - _N0); // fill rest of new hole
}
...
}
请注意,新长度较小的情况和长度相等的情况是相似的。
编辑:可以得出结论,在复制数据后字符串长度相同的情况下,必须移动/填充总共“0”个字符/孔(即不移动)。因此,实际上不需要优化,但它已经得到了微不足道的照顾。