<分区>
我正在研究 C++ 复制构造函数。我编写了使用浅拷贝构造函数的代码,该构造函数会导致研究运行时错误。我的意图是制造运行时错误。
#include <iostream>
#include <cstring>
using namespace std;
class Person{ //define Person class
char *name;
int id;
public:
Person(int id, const char *name);//constructer
~Person();//distructer
Person(Person& p){
this->name = p.name;
this->id = p.id;
}
void changeName(const char *name);
void show(){
cout << id <<',' << name <<endl;
}
};
Person::Person(int id, const char *name){
this -> id = id;
int len = strlen(name);
this->name = new char[len+1];
strcpy(this->name,name);
}
Person::~Person(){
if(name)
delete []name;
}
void Person::changeName(const char *name){
if(strlen(name) > strlen(this->name))
return;
strcpy(this->name,name);
}
int main(){
Person father(1,"Kitae");
Person daughter(father);
cout << "after object daughter maked ---" << endl;
father.show();
daughter.show();
daughter.changeName("Grace");
cout <<"daughter name changed ---"<<endl;
father.show();
daughter.show();
return 0;
}
当我在 windows 10(由 visual studio 2017 编译)上编译并运行它时,它运行良好(发生运行时错误)但它在 linux 上运行不正常(由 g++ 7.3.0 编译)(运行-time 错误不会发生)。 linux 显示没有错误发生。
因此,我在 Linux 上调试该代码。我用的是 gdb。
after object daughter maked ---
1,Kitae
1,Kitae
daughter name changed ---
1,Grace
1,Grace
[Inferior 1 (process 3297) exited normally]
可以像那个代码一样使用浅拷贝构造函数吗?如果不是,为什么 windows 和 linux 显示不同的结果?