类的交换函数

《c++ primer》13.3章节

std::swap()可以对两个同类型的对象进行交换:

struct ceshi
{
    explicit constexpr ceshi(int frist,int second)
        :frist(frist),second(second)
    {
    }
    int frist;
    int second;
};

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    ceshi c1(5,6);
    ceshi c2(40,50);

    debug c1.frist << c1.second;
    debug c2.frist << c2.second;

    std::swap(c1,c2);

    debug c1.frist << c1.second;
    debug c2.frist << c2.second;
}

std::swap是通过交换是通过创建一个临时变量赋值实现的。

    template<typename _Tp>
    inline void swap(_Tp& __a, _Tp& __b)
    {
      __glibcxx_function_requires(_SGIAssignableConcept<_Tp>)

      _Tp __tmp = _GLIBCXX_MOVE(__a);
      __a = _GLIBCXX_MOVE(__b);
      __b = _GLIBCXX_MOVE(__tmp);
    }

对于大的类如果觉得这样效率太低可以自定义类专属的交换函数:

struct ceshi
{
    explicit constexpr ceshi(int frist,int second)
        :frist(frist),second(second)
    {
    }
    int frist;
    int second;

    void swap(ceshi & c1,ceshi & c2)
    {
        qDebug()<<"调用自己的swap()";
        std::swap(c1.frist,c2.frist);
        std::swap(c1.second,c2.second);
    }
};

#define debug qDebug()<<
int main(int argc, char *argv[])
{
    ceshi c1(5,6);
    ceshi c2(10,20);

    debug c1.frist << c1.second;
    debug c2.frist << c2.second;
    
    c1.swap(c1,c2);

    debug c1.frist << c1.second;
    debug c2.frist << c2.second;
}

这里自定义交换函数,自定义只交换对象的成员变量。省去了创建一个大的临时对象的开销。

类的自定义交换函数有个应用场景:在赋值运算符里面使用swap传入一个临时对象。

    ceshi& operator=(ceshi other)
    {
        swap(*this,other);
        return *this;
    }

当前对象和传入的临时对象交换不会影响原来对象,就有了赋值的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值