赋值运算符重载函数不加&为什么会出错?
void operator=(Add n)
{
}
在赋值运算符重载的时候,这个重载函数的参数到底需不需要加&呢?不加&会发生什么?
#include <iostream>
using namespace std;
class Add
{
public:
Add(int n)
{
m_Num = new int(n);
}
void operator=(Add n)
{
if (this->m_Num != NULL)
{
delete this->m_Num;
this->m_Num = NULL;
}
this->m_Num = new int(*n.m_Num);
}
~Add()
{
if (m_Num != NULL)
{
delete m_Num;
m_Num = NULL;
}
}
int* m_Num;
};
void test01()
{
Add n1(10);
Add n2(20);
n1 = n2;
cout << *n1.m_Num << endl;
}
int main()
{
test01();
return 0;
}
让我们来运行一下上述代码,看看发生了什么:
程序显然已经崩溃了,怎么出现了这个错误呢?我们试一试加了&是什么样子?
看一下结果:
可以看到程序正常运行,也没有发生崩溃现象。
先说结论:不加&,形参是一个对象,这会形成一个临时对象,会调用拷贝构造函数发生浅拷贝问题。这个临时对象析构完,原本对象的n_Num指针维护的区域已经被释放掉了,原本对象再进行析构的时候又会再释放一次,那么这个程序就崩溃了。
那么不加&可以吗?可以的,但是要自己写一下拷贝构造函数,在形参拷贝临时对象时变成深拷贝就🆗啦。
#include <iostream>
using namespace std;
class Add
{
public:
Add(int n)
{
m_Num = new int(n);
}
Add(const Add& n)
{
cout << "拷贝构造函数调用啦" << endl;
m_Num = new int(*n.m_Num);
}
void operator=(Add n)
{
if (this->m_Num != NULL)
{
delete this->m_Num;
this->m_Num = NULL;
}
this->m_Num = new int(*n.m_Num);
}
~Add()
{
if (m_Num != NULL)
{
delete m_Num;
m_Num = NULL;
}
}
int* m_Num;
};
void test01()
{
Add n1(10);
Add n2(20);
n1 = n2;
cout << *n1.m_Num << endl;
}
int main()
{
test01();
return 0;
}
看一下运行结果:
没有任何问题!!!