copy and swap

本文介绍了一个异常安全的重载=运算符的方法,通过实现深拷贝和使用交换技巧来确保资源的安全管理。文章展示了如何为自定义类Widget重载赋值运算符,并解释了背后的设计思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  重载"="运算符,实现异常安全的

 

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值