copy and swap

  重載"="運算符,實現異常安全的

 
ios

#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>
#include "decoratorclass.h"
#include "subclass_1.h"
using namespace std;
#include "test.h"
#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();
    return 0;
}
相關文章
相關標籤/搜索