条款25:考虑写一个不抛异常的swap函数

 

注意:C++11后的std::swap模板函数,使用了移动构造函数移动赋值函数。所以。对于pimpl手法的内置类型,有移动构造函数移动赋值函数应该不用写std::swap的特化,当然写了更好。

        // TEMPLATE FUNCTION swap
template<class _Ty,
    size_t _Size> inline
    void swap(_Ty (&_Left)[_Size], _Ty (&_Right)[_Size])
        _NOEXCEPT_OP(_NOEXCEPT_OP(swap(*_Left, *_Right)))
    {    // exchange arrays stored at _Left and _Right
    if (&_Left != &_Right)
        {    // worth swapping, swap ranges
        _Ty *_First1 = _Left;
        _Ty *_Last1 = _First1 + _Size;
        _Ty *_First2 = _Right;
        for (; _First1 != _Last1; ++_First1, ++_First2)
            _STD iter_swap(_First1, _First2);
        }
    }

template<class _Ty> inline
    void swap(_Ty& _Left, _Ty& _Right)
        _NOEXCEPT_OP(is_nothrow_move_constructible<_Ty>::value
            && is_nothrow_move_assignable<_Ty>::value)
    {    // exchange values stored at _Left and _Right
    _Ty _Tmp = _Move(_Left);
    _Left = _Move(_Right);
    _Right = _Move(_Tmp);
    }

 


 

************

posted @ 2022-10-14 11:56  htj10  阅读(27)  评论(0编辑  收藏  举报
TOP