浅拷贝:浅拷贝是指只复制对象的引用,而不是对象本身。当一个对象被浅拷贝时,复制出来的新对象和原对象共享相同的内存空间。这意味着,当修改新对象时,原对象也会受到影响。C++拷贝构造函数默认提供就是浅拷贝。
浅拷贝,代码中直接把obj1.m_ptr的地址赋值给obj2.m_ptr,两者共同指向一个内存空间,可以看到运行结果中,地址是一样的,内存图如下,浅拷贝容易导致程序崩溃,如下面例子我们用delete 了obj1指向的内存,那obj的指针就成了悬空指针,即指向一个不存在的内存区域,导致程序崩溃。
#include <iostream>
using namespace std;
class myclass {
public:
myclass(int val) {
m_ptr = new int(val);
}
myclass():m_ptr(nullptr) {
}
~myclass() {
delete m_ptr;
}
//复制构造函数
myclass(const myclass& other) {
m_ptr = other.m_ptr;
}
myclass& operator=(const myclass& other) {
if (&other != this) {
m_ptr = other.m_ptr;
}
return *this;
}
public:
int* m_ptr;
};
int main() {
myclass obj1(10);
//浅拷贝
myclass obj2 = obj1;
*obj2.m_ptr =20;
cout << *obj1.m_ptr << endl;
cout << *obj2.m_ptr << endl;
cout << "obj1 address: " << obj1.m_ptr << endl;
cout << "obj2 address: " << obj2.m_ptr << endl;
return 0;
}
运行结果
20
20
obj1 address: 0x25d2630
obj2 address: 0x25d2630
内存图
深拷贝:深拷贝是指完全复制一个对象及其包含的所有数据,而不是仅复制其引用。当一个对象被深拷贝时,复制出来的新对象和原对象占用不同的内存空间,彼此独立。在 C++ 中,深拷贝通常需要自定义复制构造函数和赋值运算符。深拷贝可以避免浅拷贝带来的资源释放问题,但是同时也增加了性能的开销。
#include <iostream>
using namespace std;
class myclass {
public:
myclass(int val) {
m_ptr = new int(val);
}
myclass():m_ptr(nullptr) {
}
~myclass() {
delete m_ptr;
}
//复制构造函数
myclass(const myclass& other) {
m_ptr = new int(*other.m_ptr);
memcpy(m_ptr,other.m_ptr,sizeof(*(other.m_ptr)));
}
myclass& operator=(const myclass& other) {
//避免自我赋值
if (&other != this) {
//释放掉原来指向的资源
delete m_ptr;
m_ptr = new int(*other.m_ptr);
memcpy(m_ptr,other.m_ptr,sizeof(*(other.m_ptr)));
}
return *this;
}
public:
int* m_ptr;
};
int main() {
myclass obj1(10);
//深拷贝
myclass obj2;
obj2 = obj1;
*obj2.m_ptr = 20;
cout << *obj1.m_ptr << endl;
cout << *obj2.m_ptr << endl;
cout << "obj1 address: " << obj1.m_ptr << endl;
cout << "obj2 address: " << obj2.m_ptr << endl;
return 0;
}
运行结果
10
20
obj1 address: 0xec6330
obj2 address: 0xec6350
内存图
有问题欢迎指出。