深拷贝和浅拷贝
字符串如果进行浅拷贝会出现以下问题:
假设有两个char类型指针a,b指向同一个内存空间
当a被释放时,b还未修改,再次使用b时就会出现段错误(Linux)或内存中断(windows)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| #include<iostream>
using namespace std;
class Teacher {
public: Teacher() { m_id = 0; m_name = NULL; } Teacher(int id,const char * name) { int len = strlen(name); m_name = (char *)malloc(len + 1); strcpy(m_name, name); m_id = id; } Teacher(const Teacher & another) { cout << "Teacher(const Teacher & another).." << endl; int len = strlen(another.m_name); this->m_name = (char *)malloc(len + 1); strcpy(this->m_name, another.m_name); this->m_id = another.m_id; } void print() { cout << m_id << endl; cout << m_name << endl; cout << (int *)m_name << endl; cout << "================================================" << endl;
}
~Teacher() { if (m_name != NULL) { cout << m_name << " "; free(m_name); m_name = NULL; cout << "free" << endl; cout << "================================================" <<endl; } } private: int m_id; char * m_name;
};
void test1() { Teacher tc1(123, "xiaoh");
Teacher tc2(tc1);
tc1.print(); tc2.print();
}
int main(int argc, char* argv[]) { test1(); return 0; }
|