当前位置:网站首页>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; }
边栏推荐
- Function templates and non template functions with the same name cannot be overloaded (definition of overloads)
- .NET操作Redis Hash对象
- Review of database -- 3. SQL language
- Agenda express | list of sub forum agenda on July 27
- 2022pta平时训练题(1~10题字符串处理问题)
- Deduct daily question 838 of a certain day
- 3.1 leetcode daily question 6
- json-c库的简单使用——将json文件转换为struct.
- 关于模板函数声明与定义的问题[通俗易懂]
- Learning about tensorflow (II)
猜你喜欢
Navicat15连接本地虚拟机的Mysql(Centos7)
INSTALL_FAILED_SHARED_USER_INCOMPATIBLE错误解决方式
The difference between equals and = =
canvas上传图片base64-有裁剪功能-Jcrop.js
【Halcon视觉】编程逻辑
STM32 阿里云MQTT esp8266 AT命令
js下载文件,FileSaver.js导出txt、excel文件
Introduction to data analysis | kaggle Titanic mission
3.1 leetcode daily question 6
【Halcon视觉】图像灰度变化
随机推荐
About automatic operation on Web pages
Employee information management system based on Web
【C#语言】具名类型和匿名类型
Draco developed by Google and Pixar supports USD format to accelerate 3D object transmission & lt; Forward & gt;
js 获得当前时间,时间与时间戳的转换
Redis Docker实例与数据结构
centos8(liunx)部署WTM(ASP.NET 5)使用pgsql
Okaleido ecological core equity Oka, all in fusion mining mode
Cause: couldn‘t make a guess for 解决方法
利用原生js实现自定义滚动条(可点击到达,拖动到达)
Dynamically determine file types through links
Deduct daily question 838 of a certain day
Navicat15 MySQL (centos7) connected to local virtual machine
Function template parameters (where are the function parameters)
【Halcon视觉】阈值分割
Our Web3 entrepreneurship project is yellow
Google与Pixar开发Draco支持USD格式 加速3D对象传输<转发>
我们的Web3创业项目,黄了
Redis realizes the correct posture of token bucket
[Halcon vision] polar coordinate transformation