浅拷贝只是将变量的值赋予给另外一个变量,在遇到指针类型时,浅拷贝只会把当前指针的值,也就是该指针指向的地址赋予给另外一个指针,二者指向相同的地址;
深拷贝在遇到指针类型时,会先将当前指针指向地址包含的值复制一份,然后new一个新的内存空间,然后把复制的值放到该内存空间中,两个指针各自指向不同的地址,只是两个不同地址包含的值是相同的;
示例代码:
#include <iostream>
#include <cstring>
using namespace std;
char* shallow_copy(char* s);
char* deep_copy(char* s);
int main()
{
//shallow_copy;
char str[50] = "i like c++";
cout << "===original string!===\n";
cout << "value: " << str << endl;
cout << "adress: " << (int*)str << endl;
char* shallow_copy_str = shallow_copy(str);
cout << "===shallow copy!===\n";
cout << "value: " << shallow_copy_str << endl;
cout << "adress: " << (int*) shallow_copy_str << endl;
char* deep_copy_str = deep_copy(str);
cout << "===deep copy!===\n";
cout << "value: " << deep_copy_str << endl;
cout << "adress: " << (int*) deep_copy_str << endl;
return 0;
}
char* shallow_copy(char* s)
{
// 只是将s指向的地址复制给res指针
// res指针和s指针指向同一个地址
char* res = s;
return res;
}
char* deep_copy(char* s)
{
int len = strlen(s);
char* res = new char[len+1];
strcpy(res, s);
return res;
}
运行结果: