When should we write our own assignment operator in C++?
The answer is same as Copy Constructor. If a class doesn’t contain pointers, then there is no need to write assignment operator and copy constructor. The compiler creates a default copy constructor and assignment operators for every class.
The compiler created copy constructor and assignment operator may not be sufficient when we have pointers or any run time allocation of resource like file handle, a network connection..etc. For example, consider the following program.
1 #include<iostream>
2 using namespace std;
3
4 // A class without user defined assignment operator
5 class Test
6 {
7 int *ptr;
8 public:
9 Test (int i = 0)
10 {
11 ptr = new int(i);
12 }
13 void setValue (int i)
14 {
15 *ptr = i;
16 }
17 void print()
18 {
19 cout << *ptr << endl;
20 }
21 };
22
23 int main()
24 {
25 Test t1(5);
26 Test t2;
27 t2 = t1;
28 t1.setValue(10);
29 t2.print();
30 return 0;
31 }
Output of above program is “10″.
If we take a look at main(), we modified ‘t1′ using setValue() function, but the changes are also reflected in object ‘t2′. This type of unexpected changes cause problems.
Since there is no user defined assignment operator in the above program, compiler creates a default assignment operator, which copies ‘ptr’ of right hand side to left hand side. So both ‘ptr’s start pointing to the same location.
We can handle the above problem in two ways.
1) Do not allow assignment of one object to other object. We can create our own dummy assignment operator and make it private.
2) Write your own assignment operator that does deep copy.
Same is true for Copy Constructor.
Following is an example of overloading assignment operator for the above class.
1 #include<iostream>
2 using namespace std;
3
4 class Test
5 {
6 int *ptr;
7 public:
8 Test (int i = 0)
9 {
10 ptr = new int(i);
11 }
12 void setValue (int i)
13 {
14 *ptr = i;
15 }
16 void print()
17 {
18 cout << *ptr << endl;
19 }
20 Test & operator = (const Test &t);
21 };
22
23 Test & Test::operator = (const Test &t)
24 {
25 // Check for self assignment
26 if(this != &t)
27 {
28 *ptr = *(t.ptr);
29 }
30
31 return *this;
32 }
33
34 int main()
35 {
36 Test t1(5);
37 Test t2;
38 t2 = t1;
39 t1.setValue(10);
40 t2.print();
41 return 0;
42 }
Output:5
We should also add a copy constructor to the above class, so that the statements like “Test t3 = t4;” also don’t cause any problem.
Note the if condition in assignment operator. While overloading assignment operator, we must check for self assignment(认同测试). Otherwise assigning an object to itself may lead to unexpected results (See this). Self assignment check is not necessary for the above ‘Test’ class, because ‘ptr’ always points to one integer and we may reuse the same memory.
But in general, it is a recommended practice to do self-assignment check.
补充:
C++ doesn't allow default assignment operator to be used when there is a reference in your class.
For example, the following program produces error "error C2582: 'Test' : 'operator =' function is unavailable".
1 #include<iostream>
2 using namespace std;
3
4
5 class Test
6 {
7 int x;
8 int &ref;
9 public:
10 Test (int i):x(i),ref(x)
11 {
12 }
13 void print()
14 {
15 cout << ref;
16 }
17 void setX(int i)
18 {
19 x = i;
20 }
21 //Test &operator = (const Test &t) {x = t.x;}
22 };
23
24
25 int main()
26 {
27 Test t1(10);
28 Test t2(20);
29 t2 = t1;
30 t1.setX(40);
31 t2.print();
32 return 0;
33 }
If you uncomment the operator definition in the above program, the program works fine and prints "10".
So compiler forces to write an assignment operator when you have a non-static reference in your class.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 21:35:48
When should we write our own assignment operator in C++?的更多相关文章
- Lintcode208 Assignment Operator Overloading (C++ Only) solution 题解
[题目描述] Implement an assignment operator overloading method. Make sure that: The new data can be copi ...
- Effective C++ 第0章 copy constructor和copy assignment operator
拷贝构造函数(copy constructor)被用来以一个对象来初始化同类型的另一个对象,拷贝赋值运算符(copy assignment operator)被用来将一个对象中的值拷贝到同类型的另一个 ...
- copy constructor和copy assignment operator的区别
拷贝构造函数(copy constructor)被用来以一个对象来初始化同类型的另一个对象,拷贝赋值运算符(copy assignment operator)被用来将一个对象中的值拷贝到同类型的另一个 ...
- Default Assignment Operator and References
We have discussed assignment operator overloading for dynamically allocated resources here . This is ...
- Copy constructor vs assignment operator in C++
Difficulty Level: Rookie Consider the following C++ program. 1 #include<iostream> 2 #include&l ...
- How to use base class's assignment operator in C++
看了android下的代码,好长时间没看了,有个关于C++的知识点不是很清楚,查了下: 如何使用基类中的赋值运算符? 引述自http://stackoverflow.com/questions/122 ...
- PythonStudy——赋值运算符 Assignment operator
eg: num = 10 num += 1 # 等价于 num = num + 1 => 11 print(num) 特殊操作: 1.链式赋值 a = b = num print(a, b, n ...
- c++, 派生类的构造函数和析构函数 , [ 以及operator=不能被继承 or Not的探讨]
说明:文章中关于operator=实现的示例,从语法上是对的,但逻辑和习惯上都是错误的. 参见另一篇专门探究operator=的文章:<c++,operator=>http://www.c ...
- C++ operator overload -- 操作符重载
C++ operator overload -- 操作符重载 2011-12-13 14:18:29 分类: C/C++ 操作符重载有两种方式,一是以成员函数方式重载,另一种是全局函数. 先看例子 # ...
随机推荐
- 大白话讲解如何解决HttpServletRequest的请求参数只能读取一次的问题
大家在开发过程中,可能会遇到对请求参数做下处理的场景,比如读取上送的参数中看调用方上送的系统编号是否是白名单里面的(更多的会用request中获取IP地址判断).需要对请求方上送的参数进行大小写转换或 ...
- JMeter 5.4 打开测试计划 报错:Unexpected error
保存测试计划名为: 新增用户.jmx 关闭 JMeter 再次打开JMeter : 双击 jmeter.bat JMeter 启动 打开 新增用户.jmx Unexpected error. 看上图 ...
- CentOS8安装VirtualBox,并创建CentOS虚拟机
安装VirtualBox 执行以下命令并启用VirtualBox和EPEL包仓库 [root@localhost~] dnf config-manager --add-repo=https://dow ...
- 《手把手教你》系列技巧篇(四十二)-java+ selenium自动化测试 - 处理iframe -下篇(详解教程)
1.简介 经过宏哥长时间的查找,终于找到了一个含有iframe的网页.所以今天这一篇的主要内容就是用这个网页的iframe,宏哥给小伙伴或者童鞋们演示一下,在处理过程中遇到的问题以及宏哥是如何解决的. ...
- Python 函数 参数传递
参数传递 在 python 中,类型属于对象,变量是没有类型的: a=[1,2,3] a="Runoob" 以上代码中,[1,2,3] 是 ...
- 双非本科进大疆(SP)!
哈喽,大家好,我是仲一.今天和大家分享的是一位优秀双非本科生上岸大疆的经历(羡慕哭了...). 今年4月底的时候,这位学弟和我分享了他拿下oppo,京东,联发科实习offer的经历,当时我还发了朋友圈 ...
- [loj3278]收获
人的移动之间会相互影响,因此不妨看成果树逆时针移动,显然果树之间独立 考虑建图:1.每一棵果树向其逆时针旋转后第一个人连边:2.每一个人向其逆时针旋转不小于$C$的第一个人连边(即下一个摘的人),边权 ...
- [loj3331]选课
考虑$P=0$,由于$T-\sum_{i=1}^{m}s_{i}\le 40$,因此一个第$i$个分类中最多得到$s_{i}+42$的学分,可以对每一类分别背包 暴力背包复杂度为$o(n^{2})$, ...
- [luogu6185]序列
对于2操作,如果把这些操作看成边,那么对于某一个连通块内的若干个点,满足权值可以任意分配(证明:归纳,若n个点可以,那么先将新增的点调整好,再对原来n个点重新分配即可),因此可以将原图缩点,并将连通块 ...
- 一文明白CDN加速是个啥
作者:IT王小二 博客:https://itwxe.com 不知不觉三个月没更新了,这三个月诸事繁忙啊!最近没那么忙了,开始恢复更新. 一.CDN简介 CDN(Content Delivery Net ...