浅拷贝和深拷贝

tech2023-05-09  110

浅拷贝是不会分配新的内存的,深拷贝才能分配。 先考虑一种情况,对一个已知对象进行拷贝,编译系统会自动调用一种构造函数——拷贝构造函数,如果用户未定义拷贝构造函数,则会调用默认拷贝构造函数。 举一个例子:

#include <iostream> using namespace std; class Student { private: int num; char *name; public: Student(); ~Student(); }; Student::Student() { name = new char(20); cout << "Student" << endl; } Student::~Student() { cout << "~Student " << &name << endl; delete name; name = NULL; } int main() { { // 花括号让s1和s2变成局部对象,方便测试 Student s1; Student s2(s1); // 复制对象 } system("pause"); return 0; }

可以看到,我们在类里面有指针成员是一定要自定义拷贝构造的,否则会两次析构,造成不好的结果。

Student ~Student 0x7fff49926898 ~Student 0x7fff49926888 sh: 1: pause: not found

现在,我们成对使用new, delete开辟空间和析构:

#include <iostream> using namespace std; class Student { private: int num; char *name; public: Student(); ~Student(); Student(const Student &s); //拷贝构造函数,const防止对象被改变 }; Student::Student() { name = new char(20); cout << "Student" << endl; } Student::~Student() { cout << "~Student " << &name << endl; delete name; } Student::Student(const Student &s) { name = new char(20); cout << "copy Student" << endl; } int main() { { // 花括号让s1和s2变成局部对象,方便测试 Student s1; Student s2(s1); // 复制对象 } return 0; }

结果可以看到,两次构造,并析构了来自两个地址的内存。

Student copy Student ~Student 0x7ffcb3f1b6d8 ~Student 0x7ffcb3f1b6c8
最新回复(0)