std::swap的使用陷阱

#include <iostream>
#include <memory>
class struct1
{
public:
    static int sta_ ;
    struct1() = default;
    struct1(int x):aa(x){}
    struct1(const struct1 &s):int2_1(s.int2_1){cout << "kaobeigouzao2" << endl;}
    struct1(struct1 &&s):int2_1(s.int2_1){cout << "yidonggouzao2" << endl;}
    struct1& operator=(const struct1& s);
    struct1& operator=(struct1&& s);
    friend void swap(struct1& q ,struct1& p);

public:
    int aa = 100;
protected:
    int int2_1;
    int int2_2;
};
int struct1::sta_ = 2;
inline void swap(struct1& q ,struct1& p)
{
    using std::swap;
    swap(q.aa,p.aa);
    swap(q.int2_1,p.int2_1);
    swap(q.int2_2,p.int2_2);
}
struct1& struct1::operator=(const struct1& s) //step2进入到这个函数中
{
    struct1 ss = s; //step3调用拷贝构造
    cout << "xunhuan " << endl;
    std::swap(*this,ss); //**********这里是重点************//
                         //如果我们调用std::swap并且传入的参数是自定义类
                         //那么由于std::swap会使用到移动构造和移动赋值运算符
                         //为了能正确运行代码,就必须定义这两个移动函数
                         //否则,有移动调移动函数,没有定义则调用拷贝函数进行替代
                         //****那么在std::swap函数中就会调用本类中定义的拷贝构造和**拷贝赋值运算符**
                         //因此,反回来调用拷贝赋值运算符,又调用std::swap,就会陷入无限循环中
    return *this;
}
struct1& struct1::operator=(struct1&& s)
{
    cout << "yidongfuzhiyunsuanfu " << endl; /*这里应该对自我赋值进行检验,此处略去 */
    using std::swap;
    swap(aa,s.aa);
    swap(int2_1,s.int2_1);
    swap(int2_2,s.int2_2);
    return *this;
}

int main()
{
    struct1 str1,str11;
    str1 = str11; //step1首先调用拷贝赋值
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值