0
点赞
收藏
分享

微信扫一扫

std::swap的使用陷阱

点亮自己的那盏灯 2022-03-11 阅读 30
c++
#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);
}

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

相关推荐

0 条评论