深拷贝和浅拷贝都是针对C++中的对象、结构体和类来说的。
浅拷贝只是简单地将一个对象的数据成员的值复制到另一个对象中,两者共享同一个内存地址。这意味着如果一个对象修改了共享内存中的一个数据成员,那么另一个对象也会受到影响。这可能会导致不可预测的结果和程序错误。
以下是一个使用浅拷贝的例子:
#include <iostream>
class Person {
public:
int age;
std::string name;
Person(int _age, std::string _name) : age(_age), name(_name) {}
// copy constructor
Person(const Person& other) {
age = other.age;
name = other.name;
}
};
int main() {
Person alice(25, "Alice");
Person bob = alice; // shallow copy
alice.age = 30;
std::cout << alice.name << " is " << alice.age << " years old." << std::endl;
std::cout << bob.name << " is " << bob.age << " years old." << std::endl;
return 0;
}
输出:
Alice is 30 years old.
Alice is 30 years old.
在使用浅拷贝时,通过修改一个对象的数据成员的值也会修改另一个对象的数据成员的值。
深拷贝则是在拷贝对象时,在堆上分配新的内存空间来存储数据成员的值,这样两个对象互不干扰。这是一个使用深拷贝的例子:
#include <iostream>
class Person {
public:
int age;
std::string* name;
Person(int _age, std::string _name) : age(_age), name(new std::string(_name)) {}
// copy constructor
Person(const Person& other) {
age = other.age;
name = new std::string(*(other.name));
}
// destructor
~Person() {
delete name;
}
};
int main() {
Person alice(25, "Alice");
Person bob = alice; // deep copy
alice.age = 30;
*(alice.name) = "Alicia";
std::cout << alice.name << " is " << alice.age << " years old." << std::endl;
std::cout << bob.name << " is " << bob.age << " years old." << std::endl;
return 0;
}
输出:
Alicia is 30 years old.
Alice is 25 years old.
在使用深拷贝时,通过修改一个对象的数据成员的值不会影响另一个对象的数据成员的值。