operator=处理自我赋值
2014-07-01 20:52
162 查看
有许多时候,我们自己编写类的operator=函数(例如,当类中包含指针时)。
考虑如下的一个类:
不仅仅删除了当前对象的val, 也删除了rhs 的 val. 那么 rhs.val 指向的就是一个已经被删除的int. 这必然产生诡异的问题。
但是上述做法,虽然具有自我复制安全性,但是不具有异常安全性。
如果 new int 抛出异常的时候,this->val 指向的就是一个已经删除的int
考虑如下的一个类:
class Widget { public: Widget(int x=0): val(new int(x)) {} ~Widget() { delete val; } Widget(const Widget &rhs): val(new int(*rhs.val)) {} //operator = Widget& operator=(const Widget &rhs); void print() const { cout << *val << endl; } private: int *val; };
错误版本:
当自我赋值的时候,下面的代码是不安全的。如果*this 和 rhs 是同一个对象,那么第一句 delete val;不仅仅删除了当前对象的val, 也删除了rhs 的 val. 那么 rhs.val 指向的就是一个已经被删除的int. 这必然产生诡异的问题。
/** wrong version * not-safe when self-assignment occurs. */ Widget& Widget::operator=(const Widget &rhs) { delete val; val = new int(*rhs.val); return *this; }
改进版本1:
阻止此类错误的传统做法是加一个证同测试(identity test)。Widget& Widget::operator=(const Widget &rhs) { if(this == &rhs) return; delete val; val = new int(*rhs.val); return *this; }
但是上述做法,虽然具有自我复制安全性,但是不具有异常安全性。
如果 new int 抛出异常的时候,this->val 指向的就是一个已经删除的int
改进版本2:
异常安全性与自我复制安全性兼具Widget& Widget::operator=(const Widget &rhs) { int *pOld = val; val = new int(*rhs.val); delete pOld; return *this; }
改进版本3:
copy and swap 技术Widget& Widget::operator=(const Widget &rhs) { Widget temp(rhs); swap(temp); return *this; }
改进版本4:
通过传值来实现 copy and swapWidget& Widget::operator=(Widget rhs) { //yes, copy by value swap(rhs); return *this; }
相关文章推荐
- 条款11:在operator=中处理”自我赋值“
- 条款11: 在operator= 中处理"自我赋值"
- 条款十一 在operator = 中处理"自我赋值"
- 条款11 在operator=中处理“自我赋值”
- 条款11:在operator=处理自我赋值
- Effective C++ Item 11 在operator= 中处理“自我赋值”
- 《Effective C++》item11:在operator=中处理“自我赋值”
- 在operator=中处理自我赋值
- 条款11:在operator=中处理“自我赋值”
- 读书笔记 effective c++ Item 11 在operator=中处理自我赋值
- Effective C++ 条款11:在operator=中处理"自我赋值"
- Effective C++ 条款10 令operator=返回一个reference to *this 条款11 在operator=中处理"自我赋值"
- C++中在operator=中处理“自我赋值”(11)---《Effective C++》
- effective c++条款11 在operator=中处理“自我赋值”
- 条款11:在operator = 中处理“自我赋值”
- Effective C++条款11解读: 在operator=中处理“自我赋值”------顺便给出string类的Big Three
- 用3种方法在 operator= 中处理“自我赋值”
- Effective C++ Item 11-在operator = 中处理"自我赋值"
- 条款11:在operator = 中处理"自我赋值"
- 条款11:在operator=中处理“自我赋值”