当前位置:网站首页>Self assignment and abnormal security problems in operator=
Self assignment and abnormal security problems in operator=
2022-07-23 09:34:00 【Just call me Xiao Qin】
introduction
We overload the assignment operator in the class (operatro =) When it comes to Self assignment and Abnormal safety The problem of , Now let's solve these two problems step by step .
Problems arise
Self assignment
Cited example
Self assignment When an object is assigned to itself :
class Person {
... };
Person p;
...
p = p;
It looks a little stupid , But there is no doubt that it is legal , Let's not assume that this kind of thing will never happen .
In addition, assignment actions are not always recognizable at a glance , for example :
arr[i] = arr[j] // Potential self assignment
*pa = *pj // Self assignment caused by pointer pointing
int p = 0; // Self assignment caused by reference
int& rp = p;
...
p = rp;
If we write the following code :
class Teacher {
... };
class Student
{
...
private:
Teacher* t;
};
Student& Student::operator=(const Student& rt)
{
delete t;
t = new Teacher(*(rt.t));
return *this;
}
The self assignment problem here is ,opreator= Functional *this( Assignment destination ) and rt It could be the same object . If so delete It's not just about destroying the current object Teacher It's also destroyed rt Of Teacher. At the end of the function ,Student This will not change because of self assignment , Now it holds a pointer to a deleted object .
Method
The traditional solution is to operator Add a test at the top to achieve the purpose of self assignment :
Student& Student::operator=(const Student& rt)
{
// This detection method needs to ensure Student And Teacher It's a one-to-one relationship
// That is, there can be no difference Stu The pointer of points to the same Tea The situation of , Otherwise, it will also cause the above problems
// if (this != &rt)
if (this->t != rt.t)
{
delete t;
t = new Teacher(*(rt.t));
}
return *this;
}
This does have self assignment security , But it does not have abnormal security .
Abnormal safety
The above code has trouble with exceptions , More specifically , If new Teacher Cause exception ( Insufficient memory during allocation or because Teacher The copy constructor of throws an exception ),Student Eventually, it will hold a pointer to a deleted Teacher. You cannot safely delete them , You can't even read them safely .
resolvent
We can apply for space first , Then delete the original space . such , Even if an exception is thrown when applying for space , The original pointer will not be affected .
Student& Student::operator=(const Student& rt)
{
// Performing the test can clearly show that we have considered the situation of self assignment
if (this->t != rt.t)
{
Teacher* tmp = t; // Remember the original t
tmp = new Teacher(*(rt.t)); // Make t Point to the new space
delete tmp; // Delete the original t
}
return *this;
}
// This version can remove the front detection of the function , Self assignment can be completed even without detection
// The premise is also that there can be no difference Stu The pointer of points to the same Tea The situation of , Otherwise, it will cause strange problems
// This may be inefficient in self assignment , But the detection itself needs cost and the frequency is not high
Student& Student::operator=(const Student& rt)
{
Teacher* tmp = t; // Remember the original t
t = new Teacher(*(rt.t)); // Make t Point to the new space
delete tmp; // Delete the original t
return *this;
}
copy and swap technology
We can also use copy construction to complete this function :
class Student
{
...
void swap(Student& rs); // In exchange for *this and rs The data of
...
};
Student& Student::operator=(const Student& rs)
{
Student tmp(rs); // by rs Make a copy of the data
swap(tmp); // take *this Data and tmp Data exchange of
// tmp Will be out operator= Auto destroy after scope
return *this;
}
// If the assignment overload adopts value transfer and parameter transfer
Student& Student::operator=(const Student rs)
{
swap(rs); // take *this Data and rs Data exchange of
return *this;
}
边栏推荐
猜你喜欢

Repeat: the difference between Pearson Pearson correlation coefficient and Spearman Spearman correlation coefficient

C语言经典练习题(1)——“水仙花数“

【bug 简单处理】

Vs Code shortcut key settings

PyG利用MessagePassing搭建GCN实现节点分类

The pit trodden by real people tells you to avoid the 10 mistakes often made in automated testing

服务器内存性能调优

Double disk: what is a b+ tree? Do you know how b+ trees build ordered tables? What are the characteristics of b+ tree

如何高效系统学习 MySQL?

判断是否为void类型
随机推荐
正则表达式
pytorch中的 nn.ModuleList 和 nn.Sequential
广发期货可以开户吗?安全吗
SPSS Chi-Square
canal 第6篇
Déterminer s'il s'agit d'un type vide
What is the combined effect of compose and recyclerview?
Pytorch visualization
Emmet 语法简结
AIRIOT答疑第5期|如何使用低代码业务流引擎?
[LeetCode]剑指 Offer 61. 扑克牌中的顺子
复盘:什么是B+树?你知道B+树怎么构建有序表的吗?B+树有什么特点
RNA 25. SCI文章中只有生信没有实验该怎么办?
Event listening and deleting events - event object - default event - cancel bubbling event - event delegation - default trigger
服务器内存性能调优
READ-COMMITTED没有区间锁
canal 第8篇
肽核酸(PNA)偶联穿膜肽(CCPs)(KFF)3K形成CCPs-PNA|肽核酸的使用方法
transformer汇总
stb_image代替其他库