当前位置:网站首页>11 在 operator= 中处理“自我赋值”
11 在 operator= 中处理“自我赋值”
2022-07-26 10:32:00 【JeffyGao】
条款- 11 在 operator= 中处理“自我赋值”
- 确保当对象自我赋值时 operator= 有良好行为。其中技术包括比较“来源对象” 和 “目标对象”的地址、精心周到的语句顺序、以及 copy-and-swap。
- 确定任何函数如果操作一个以上的对象,而其中多个对象是同一个对象时,其行为仍然正确。
“自我赋值”很容易被使用,虽然没有意义,但若不加以 处理会造成系统报错。
法 1 传统做法:在 operator= 里做一个“证同测试( identity test )”达到“自我赋值”的检测目的。
widget& widget::operator=( const widget& rhs ){ if ( this == &rhs ) return *this; // 证同测试( identity test ) // 如果是自我赋值,就不做任何事 delete pb; pb = new Bitmap( *rhs.pb ); return *this; }法2 拷贝副本,让operator= 具备异常安全性
widget& widget::operator=( const widget& rhs ){ Bitmap* pOrig = pb; // 记住原先的 pb pb = new Bitmap( *rhs.pb ); // 令 pb 指向 *pb 的一个副本 delete pOrig; // 删除原先的 pb return *this; }
边栏推荐
猜你喜欢
随机推荐
头歌 Phoenix 入门(第1关:Phoenix 安装、第2关:Phoenix 基础语法)
少了个分号
datav漂亮数据屏制作体验
Review of database -- 3. SQL language
数据分析入门 | kaggle泰坦尼克任务(一)—>数据加载和初步观察
L2-005 集合相似度(vector、set求并交集)
函数模板参数(函数参数在哪)
软件打不开了
Android greendao数据库的使用
简单化构造函数的继承方法(二)- ES6中的class继承
数据库的复习--1.概述
【Halcon视觉】图像的傅里叶变换
Learning about tensorflow (I)
About the declaration and definition of template functions [easy to understand]
Navicat15连接本地虚拟机的Mysql(Centos7)
Inheritance method of simplified constructor (I) - combined inheritance
Function template parameters (where are the function parameters)
[C language] LINQ overview
Self encapsulated database dbutils universal template
面试第二家公司的面试题及答案(二)


![[Halcon vision] morphological corrosion](/img/f9/f01dd3340824ff28c84cf7bb52882e.png)



![[Halcon vision] affine transformation](/img/f1/32284c71e78e6eea390fdb6058ba0f.png)

