我是一年级学生,这是我第一次在stackoverflow中询问。最近,我的教授给我发了一条代码,要求我找出它有什么问题。
#include <iostream>
#include <cstring>
using namespace std;
class A
{
public:
A(int c);
~A();
int code;
char *name;
};
A::A(int c)
{
code = c;
name = new char[50];
if(name == 0)
{
cout << "Unavailable memory" << endl;
exit(1);
}
}
A::~A()
{
cout << "Delete pointer to " << name << endl;
delete [] name;
}
int main(void)
{
A a1(100), a2(200);
strcpy(a1.name, "Mike");
a2 = a1;
strcpy(a2.name, "Peter");
cout << a1.name << endl;
return 0;
}
据我所知,在调用对象a2的析构函数后,程序应该崩溃,因为对象a1的析构函数将尝试删除相同的已删除的内存。在此行之后:
a2 = a1;
对象a2的char *指向对象a1指针所指向的相同地址,因此在调用析构函数时会产生混乱。对我来说真正没有意义的是程序运行完美的事实现在很好没有任何崩溃,但是昨天程序在控制台上崩溃了以下输出:
Delete pointer to Peter
Delete pointer to [insert strange characters here]
Process exited with return value 344233377
所以即时通讯询问是否有人可以启发我关于这个程序的奇怪行为.BTW是否更好地使用像这样的运算符重载
#include <iostream>
#include <cstring>
using namespace std;
class A
{
public:
A(int c);
~A();
A operator=(A a1);
int code;
char *name;
};
A::A(int c)
{
code = c;
name = new char[50];
if(name == 0)
{
cout << "Unavailable memory" << endl;
exit(1);
}
}
A::~A()
{
cout << "Delete pointer to " << name << endl;
delete [] name;
}
A A::operator=(A a1)
{
*name=*a1.name;
code=a1.code;
return *this;
}
int main()
{
A a1(100), a2(200);
strcpy(a1.name, "Mike");
a2 = a1;
strcpy(a2.name, "Peter");
cout << a1.name << endl;
return 0;
}
或者我应该使用类似复制构造函数的东西吗?