自我赋值

  1. class Widget {……};
  2. Widget w;
  3. w = w;
  4. //有可能发生的自我赋值
  5. a[i] = a[j]; //i = j的话
  6. *p = *q; //q和q指向同一块内存
  7. class Base {……};
  8. class Derived : public Base {};
  9. void doSomething(const Base& b,Derived& d); //b和d
  10. 如果两个对象,来自于同一个继承体系,也有可能指向同一块内存空间

版本一:自我赋值安全

  1. #include<iostream>
  2. using namespace std;
  3. class Bitmap {};
  4. class Widget {
  5. public:
  6. Widget& operator=(const Widget& rhs) {
  7. delete bitmap;
  8. bitmap = new Bitmap(*rhs.bitmap); //调用拷贝构造,rhs.bitmap的副本
  9. //而不是bitmap = rhs.bitmap,这是一个浅拷贝
  10. return *this;
  11. }
  12. private:
  13. Bitmap *bitmap;
  14. };
  15. int main() {
  16. Widget w;
  17. w = w;
  18. return 0;
  19. }

image.png
1、bitmap = new Bitmap( rhs.bitmap ); this->bitmap所指向的空间和rhs->bitmap一样,当自我赋值时,this->bitmap所指向的空间已经被删除,所以rhs->bitmap指向的是一个已经被删除的空间
2、空指针(与本例关系不大)
1)异常的解释,本例中是因为给空指针赋值了
2)为什么不能给空指针赋值
因为NULL本质就是0,则,一个指针变量的值为0,意味着它指向整个内存的最开始字节处,而这个地方是用户程序(APP)的禁区,不能访问,如果强行访问,则,将被OS禁止并中断这个进程执行(程序被中断)。
上述说法,不能说指针的值不能为NULL,只是说,不能对0编号开始的空间进行“访问”。即,可以令指针指向0编号区域,只要不访问就没有问题。
3)如果在delete bitmap之后,bitmap = NULL,此时bitmap才是空指针,光delete bitmap还不是空指针,只是删除了bitmap所指的地址空间,还可以给bitmap指针赋值
3、
+ 指针,才可以直接得到指针所指变量的内容,比如:
int a = 10;int p = &a;
cout <<
p << endl;

版本二:异常安全

  1. Widget& operator=(const Widget& rhs) {
  2. if(this == &rhs) return *this;
  3. delete bitmap;
  4. bitmap = new Bitmap(*rhs.bitmap);
  5. return *this;
  6. }

bitmap = new Bitmap( *rhs.bitmap ); 虽然规避了自我赋值导致的异常,但是拷贝构造抛出异常 或者 内存不够了,bitmap指向了被删除的空间
这种指针如果不使用倒是可以正常运行,一旦使用就会带来麻烦

版本三:if的成本

  1. Widget& operator=(const Widget& rhs) {
  2. Bitmap *oldMap = bitmap;
  3. delete oldMap;
  4. bitmap = new Bitmap(*rhs.bitmap);
  5. return *this;
  6. }

效率没有带 if 的高,但是if也是有成本的,要判断发生自我赋值的频率

版本四:copy on write

  1. class Widget {
  2. public:
  3. ……
  4. //交换*this和rhs
  5. void swap(Widget& rhs) {
  6. ……
  7. }
  8. Widget& operator=(const Widget& rhs) {
  9. Widget temp(rhs);
  10. //必须将非const的Widget对象传入swap函数
  11. swap(temp);
  12. return *this;
  13. }
  14. //或者
  15. Widget& operator=(Widget rhs) {
  16. swap(rhs);
  17. return *this;
  18. }
  19. };

a = b,交换a( *this )和b( rhs )地址空间的内容

总结

设计operator=时,要考虑自我赋值(保证这种情况是合法的)、语句顺序和copy and swap