c++赋值操作符需要确保自我赋值的安全性问题

class tmp
{
public:
    int a;
    int b;
};

class ctest
{
public:
    ctest()
    {
        p = new tmp;
    }

    ~ctest()
    {
        delete p;
    }

    ctest& operator = (const ctest& t)
    {
        tmp * tmpptr = p;    //能够保证自我赋值的安全性问题;
        p = new tmp(*t.p);    //触发系统的默认拷贝构造函数,浅拷贝;
        delete tmpptr;

        return *this;
    }

public:
    tmp *p;
};


int main()
{
    ctest t;
    t.p->a = 1;
    t.p->b = 2;
    printf("%p\n", t.p);

    t = t;
    printf("%p\n", t.p);
    cout << t.p->a << ":" << t.p->b << endl;
    return 0;
}

 

posted @ 2021-03-25 20:26  唯一诺  阅读(96)  评论(0)    收藏  举报