关于operator=中自我复制以及异常安全的处理

赋值构造函数主要遇到问题有有自我赋值的可能,因为赋值过程中可能要删除原来对象存储的指针数据,所以需要先检查是否是自我赋值,然后再删除;但是再赋值过程中可能出现异常,比如new分配新的空间过程

class Widget
{
    public:
    Widget& operator=(const Widget& rhs)
    {
        if(rhs==this)
            return *this;
        delete ch;
        ch=new char(*rhs.ch);//可能遇到异常,导致ch已经被删除,导致ch指向一个被删除的空间
        return *this
    }
    private:
        char* ch;
};
class Widget
{
    public:
    Widget& operator=(const Widget& rhs)
    {
        char* pt=ch;//通过合理安排赋值顺序,避免异常
        ch=new char(*rhs.ch);
        delete pt;
return *this; }
private: char* ch; };

 

class Widget
{
    public:
    Widget& operator=(const Widget& rhs)
    {
        Widget temp(rhs);
        w_swap( temp);//通过swap函数规避异常,临时对象在函数退出时,自动分解(copy-and-swap方法)
        return *this;
    }
    void w_swap(const Widget& rhs)
    {
        char* tem=ch;
        ch=rhs.ch;
        rhs.ch=tem;
    }
    private:
        char* ch;
};

 

posted on 2015-11-22 19:04  菜鸟基地  阅读(164)  评论(0)    收藏  举报

导航