zhx6044的个人主页

http://www.qtcn.org/bbs/u/118368  [收藏] [复制]

zhx6044

  • 12

    关注

  • 4

    粉丝

  • 28

    访客

  • 等级:新手上路
  • 总积分:28
  • 保密,2011-06-21

最后登录:2015-05-27

更多资料

日志

copy and swap

2012-06-05 14:50
             重载"="运算符,实现异常安全的
            
#ifndef WIDGET_H#define WIDGET_H#include <iostream>using namespace std;class Widget{public:    Widget(int* elem);    ~Widget(){delete _elem;cout<<"~~~"<<endl;}    Widget(const Widget& co);    Widget& operator=(const Widget& co);    void swap(Widget& co);    void show() const{cout<<*_elem<<endl;}private:    int* _elem;};
#endif // WIDGET_H#include "widget.h"
Widget::Widget(int *elem):_elem(elem){    }Widget::Widget(const Widget &co){    _elem = new int(*co._elem);}Widget& Widget::operator=(const Widget&co){    Widget temp(co);    swap(temp);    return *this;}void Widget::swap(Widget &co){    int *temp = _elem;    _elem = co._elem;    co._elem = temp;//交换了地址,原先的地址会在局部变量的析构中释放}#include <iostream>using namespace std;#include "widget.h"
int main(){    Widget w1(new int(2));    cout<<"show w1_elem:";    w1.show();    Widget w2(new int(4));    cout<<"show w2_elem:";    w2.show();    cout<<"w1 = w2";    w1 = w2;//赋值的过程中使用了一个局部变量,所以在运行时有三次“~~”输出,不要奇怪    cout<<"show w1_elem:";    w1.show();
}
分类:C/C++|回复:0|浏览:1429|全站可见|转载
 

下一篇: QT 一些非常常用的操作

上一篇: 修饰器

Powered by phpwind v8.7 Certificate Copyright Time now is:05-06 20:52
©2005-2016 QTCN开发网 版权所有 Gzip disabled