在未定义显示拷贝构造函数的情况下,系统会调用默认的拷贝函数——即浅拷贝,它能够完成成员的一一复制。
在某些状况下,类内成员变量需要动态开辟堆内存,如果实行位拷贝,也就是把对象里的值完全复制给另一个对象,如A=B。这时,如果B中有一个成员变量指针已经申请了内存,那A中的那个成员变量也指向同一块内存。这就出现了问题:当B把内存释放了(如:析构),这时A内的指针就是野指针了,出现运行错误。
mystring.h
#ifndef MYSTRING_H
#define MYSTRING_H
class mystring{
private:
char *s;
public:
mystring();
mystring(const char *s);
~mystring();
char *get_s();
void set_s(const char *s);
};
#endif // MYSTRING_H
mystring.cpp
#include <iostream>
#include <string.h>
#include "mystring.h"
using namespace std;
mystring::mystring():s(NULL){
}
mystring::mystring(const char *s){
int len =strlen(s);
this->s = new char[len+1];
strcpy(this->s,s);
this->s[len] = 0;
}
mystring::~mystring(){
delete []s;
}
char *mystring::get_s()
{
printf("s Memory address is %p\n",&this->s);
return s;
}
void mystring::set_s(const char *s){
strcpy(this->s,s);
}
main.cpp
#include <iostream>
#include <mystring.h>
using namespace std;
int main(){
char *name = "wunanhui";
mystring str1(name);
mystring str2 = str1;
cout << "1" << str1.get_s() << endl;
cout << "2" << str2.get_s() << endl;
str1.set_s("wuchanzhu1");
str2.set_s("wuchanzhu2");
cout << "3" << str1.get_s() << endl;
cout << "4" << str2.get_s() << endl;
return 0;
}
结果
s Memory address is 0028fea8
1wunanhui
s Memory address is 0028fea4
2wunanhui
s Memory address is 0028fea8
3wuchanzhu2
s Memory address is 0028fea4
4wuchanzhu2